SQL name instead of ID in many to many relation - sql-server

I am trying to make simple chat with database. So I created 2 tables:
Users (ID(PK), Name, Password)
Messages (ID(PK), senderID(FK from users), recipientID(FK from users)), text
I am really noob in SQL and I just can't write query that will return table Messages but with normal names instead of senderID and recipientID. Also I didn't find examples where 1 table uses twice, so JOIN didn't work for me, or I used it in wrong way.

SELECT US.Name as SenderName, UR.Name as RecipientName, M.text
FROM Messages M JOIN Users US ON US.ID = M.senderID
JOIN Users UR ON UR.ID = M.recipientID

Not sure if I understand your question correctly, or which db you are using but this is what I think you are looking for:
SELECT Messages.text, Users.name
FROM Messages
inner JOIN Users
ON Messages.sender_id = Users.id

Related

How to JOIN 2 Tables in SalesForce (SOQL)

I'm new to SalesForce and SOQL and was surprised that simple JOIN can become a real problem for me.
There are 2 Tables (Account and Intake__c) that I want to INNER JOIN. The only data I need from Account Table is Client Name (Name).
I was able to run 2 queries separately with no errors.
Account:
SELECT
a.Id,
a.Name
FROM Account AS a
Intake__c:
SELECT
i.Client_Id__c,
i.Intake_Id__c,
i.Intake_Name__c,
i.Intake_Status__c
FROM Intake__c AS i
However, when I try to join them, I get the error:
MALFORMED_QUERY: ERROR at Row:1:Column:151 unexpected token: 'JOIN'
SELECT
i.Client_Id__c,
a.Name,
i.Intake_Id__c,
i.Intake_Name__c,
i.Intake_Status__c
FROM Intake__c AS i
JOIN Account AS a
ON (i.Client_Id__c = a.Id)
SOQL syntax for joins is special, looks bit object-oriented. https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_relationships_and_custom_objects.htm
You probably need
SELECT Client_Id__r.Name, Intake_Id__c, Intake_Name__c, Intake_Status__c
FROM Intake__c
The "__r" bit is called relationship name and acts bit like a table alias in JOIN. You can travel via "dot" up to 5 times (see, "object-oriented").
And if you'd need a top-down approach (left outer join starting from account) it'd probably be something like
SELECT Id, Name,
(SELECT Intake_Status__c FROM Intakes__r)
FROM Account

Self Joins in Laravel 8 Framework

I'm working on this project were I'm using Laravel 8 as my backend frame work and I have to make a self Join, I have tried out this code but it did not work -the first join is the one I tried but failed- :
public function get_all_medical_centers(){
$data= DB:: table('medicalcenters')
->join('medicalcenters','medicalcenters.id',"=",'medicalcenters.parent_id')
->join('countries','medicalcenters.country_id',"=",'countries.id')
->join('states','medicalcenters.country_id',"=",'states.id')
->join('cities','medicalcenters.country_id',"=",'cities.id')
->select('medicalcenters.*', 'countries.name as country_name', 'states.name as state_name', 'cities.name as cities_name')
->get();
return $data;
}
The thing is, in the database the medical centers table has some attributes that are the parent of other attributes and I want to get the name of the parent attribute when previewing the children to also preview the name of its parent and not just the id.
the table diagram:
If you try to self-join a table then you have to give at least one of them an alias, because otherwise, SQL can't know what you are referring to if you select any column from those tables.
To add an alias to your joined table, you can do this:
DB::table('medicalcenters AS medc')
->join('medicalcenters AS self','medc.id',"=",'self.parent_id')
But this is a hacky solution and for normal relational data in Laravel, eloquent models would better.
Edit Why do you need Aliases on self joins:
If you join two tables, lets say: users join posts on users.id = posts.user_id. You have to specify the join condition. Here this is users.id = posts.user_id.
Lets modify this to a self join: users join users on users.id = users.user_id. Here the condition is not clear. Is this users.id or this users.user_id the original table or the self joined table? It's not clear how to join those two tables. So we have to give them different names aka aliases. Like this users as creators join users as subscribers on creators.id = subscribers.user_id.

SQL Sub Query when joining table

I am back to a similar issue I have had previously. It should be a simple thing, but cannot get my head around it. Here is an overview of the tables and what I am trying to achieve with this subquery. I am using SQL Server 2008.
Users
This contains a list of users
Login Audit
Contains a list of login attempts. It holds the userID and the loginDate (datetime field)
What I am trying to achieve
I want to be able to show rows of users and their last login date from the audit table.
Here is my query, that would make sense from a laymans perspective! ;-)
SELECT u.userID, u.fName, u.sName, l.loginDate
FROM Users AS u LEFT OUTER JOIN
(SELECT TOP (1) loginDate, userID
FROM LoginAudit) AS l ON l.userID = u.userID
WHERE (u.cliID = 1)
This just pulls back the last loginDatefor the last user that logged in. I wanted all of the users to come back regardless if they logged in or not.
Any assistance would be appreciated.
Thanks
nick
select a.userid, a.fName, a.sName,
max(b.loginDate)
from
users a
left outer join lastLogin b on a.userid = b.userid
group by a.userid, a.fName, a.sName
You want to replace your subquery with
SELECT userID, max(loginDate) as lastLogin FROM LoginAudit GROUP BY userID
And then replace "l.loginDate" in your main query with "l.lastLogin"
The functionality you want is provided by the MAX() function in an aggregate query, not the TOP() function.

FreeTextTable across two related tables

I have Client table and a Contact table. A Client can have multiple contacts, contact table has a FK to a Client PK.
I need a FreeTextTable query so I can search by Client Name or Contact Name.
I've been trying to UNION FreeTextTable results from each table without much luck.
Any ideas?
Soemthing like this should work for you:
SELECT *
FROM Client A
LEFT JOIN Contact B
ON A.ClientId = B.ClientId
WHERE A.ClientName LIKE '%somename%' OR B.ContactName LIKE '%somename%'

SQL Subquery in LINQ for Entity Framework 4.0

I'm new to LINQ and EF, but I've been able to stumble through for the majority of the queries I have, but this one has me completely confused. No matter what I try, it comes up in SQL Profiler as a big mess :-).
I have two tables: Users and UsersProjects. The goal of this query is to list all the users who are working on projects with the specified user. Here is the query as I have it written in SQL. It's a subquery, but I don't know of a way to simplify it further, but I'm open to suggestions there as well.
SELECT DISTINCT Users.FirstName, Users.LastName
FROM Users INNER JOIN UsersProjects ON Users.ID=UsersProjects.UserID
WHERE UsersProjects.ProjectID IN
(SELECT ProjectID FROM UsersProjects WHERE UserID=#UserID)
Anybody able to help?? It seems like a fairly simple subquery in SQL, but in LINQ, I'm baffled.
Thanks,
Jorin
Something like this I guess:
from u in Users
from projectId in UsersProjects.Where(up => up.UserId == #userId).Select(p => p.ProjectId)
where u.UsersProjects.Any(up => projectId == up.ProjectId)
select u
or (it's your sql query in linq)
(from u in Users
join up in UsersProjects on #userId equals up.UserId
where u.UsersProjects.Any(up2 => up2.ProjectId == up.ProjectId)
select u).Distinct()

Resources