答案 0 :(得分:1)
你应该做2个连接,一个用于获取每个朋友的ID,另一个用于检索该朋友的姓名。
SELECT
U.ID,
U.first_name,
U.last_name,
N.first_name FriendFirstName,
N.last_name FriendLastName
FROM
[user] U
LEFT JOIN firends F ON U.ID = F.user_id
LEFT JOIN [user] N ON F.friend_id = N.id
使用LEFT JOIN
会让您看到没有朋友的人(嗅探)。
如果您想要查看特定用户:
SELECT
U.ID,
U.first_name,
U.last_name,
N.first_name FriendFirstName,
N.last_name FriendLastName
FROM
[user] U
LEFT JOIN firends F ON U.ID = F.user_id
LEFT JOIN [user] N ON F.friend_id = N.id
WHERE
U.ID = 1948 -- Supplied ID
答案 1 :(得分:1)
自我join
s
select f.first_name, u.first_name as friend_name
from user u
join (
select u.first_name, f.friend_id
from friend f
join user u on u.id = f.user_id
) f on f.friend_id = u.id
答案 2 :(得分:0)
一个简单的内连接将
Select First_name,Last_name
from user inner join friends on user.id = friends.user_id
where friends.id = 1
如果您想查看friends.user_id = 1
列,可以使用user_id
替换
答案 3 :(得分:0)
也许我错了,但这是我的建议:
SELECT
u1.first_name,
u1.last_name,
u2.first_name AS FriendFirstName,
u2.last_name AS FriendLastName,
FROM user AS u1
INNER JOIN friends AS f
ON t1.id = f.user_id
INNER JOIN user AS u2
ON f.friend_id = u2.id