Reputation: 101
i have a table setup as the folowing
I am trying to write one query to return the result where status=1 confirmed =1 and user ID=specified. I want the result to dispay the user id , the name associated to that user id, the freind id and the name associated to that freind id. So far following tutorials on the web i have come up with the following query
SELECT `freinds.User ID`, `freinds.Freind ID`, `users.User`, `users.User` FROM `freinds` WHERE `User ID`= 6 INNER JOIN `users` on `users.ID`=6 AND `users.ID`=`freinds.Freind ID`
However i am getting an sql error with this query. I think what i am supposed to do is Inner join the user table twice but i am not exactly sure as to how to do it
Upvotes: 3
Views: 74
Reputation: 263853
the problem is you have wrap the tablename and columnname with backtick as a whole. you need to separate it, or if the name is not on `MySQL Reserved Keywords, remove the backticks.
You also need to join the table User
twice so you can get the names for each ID on table Freinds
.
SELECT a.`User ID`,
a.`Freind ID`,
b.User FriendName,
c.User UserName
FROM `freinds` a
INNER JOIN `users` b
ON b.ID = a.`Freind ID`
INNER JOIN users c
ON c.id = a.`user ID`
WHERE `User ID`= 6
As a sidenote, if one of the ID
is nullable, LEFT JOIN
is preferred than INNER JOIN
.
To fully gain knowledge about joins, kindly visit the link below:
Upvotes: 2