使用friends表从users表中选择firstnames和lastnames

时间:2015-04-22 20:24:54

标签: php html mysql sql

好的,所以我设法为用户75选择了朋友ID,我怎么能弄清楚如何从用户表中为朋友ID选择users.firstname,users.lastname 我不能删除IF声明,因为我的朋友之一会被淹没,因为这会破坏其他查询。

SELECT IF(friends.sender = 75, friends.recipient, friends.sender) users.firstname, users.lastname AS user_id
FROM friends
JOIN users 
ON (users.id = friends.sender)
WHERE friends.sender = 75
    OR friends.recipient = 75

1 个答案:

答案 0 :(得分:2)

在子查询中选择好友ID,然后将其加入users

SELECT u.firstname, u.lastname
FROM users as u
JOIN (SELECT DISTINCT IF(friends.sender = 75, friends.recipient, friends.sender) AS friend
      FROM friends
      WHERE 75 in (sender, recipient)) AS f
ON f.friend = u.id