从MySQL获取朋友姓名列表

时间:2012-03-12 13:07:41

标签: php mysql left-join

我有一张名为friends的表;

    friends
id   uid   fid
1     1     2   (1 is a friend of 2 and vice versa)
2     1     3   (1 is a friend of 3 and vice versa)
3     4     1   (1 is a friend of 4 and vice versa)
4     5     1   (1 is a friend of 5 and vice versa)

并为用户提供相应的表格;

  users
uid  name
1    mike
2    john
3    karl
4    mary
5    tony

这似乎不起作用:

SELECT name FROM users LEFT JOIN friends ON friends.uid=users.uid WHERE friends.uid='1' OR friends.fid='1'

我的查询应该是什么来获取迈克朋友的所有名字?

6 个答案:

答案 0 :(得分:2)

未测试:

SELECT name from friends LEFT JOIN users on users.uid=friends.fid where friends.uid=1 UNION 
SELECT name from friends LEFT JOIN users on users.uid=friends.uid where friends.fid=1

如果有人与自己成为朋友,这看起来有点奇怪。

答案 1 :(得分:2)

尝试以下其中一项:

SELECT a.uid as UserID,
       a.`Name` as UserName,
      c.`Name as FriendsName
FROM users a LEFT JOIN friends b on a.uid = b.uid
    LEFT JOIN users c on b.fid = c.uid

OR

SELECT a.uid as UserID,
       a.`Name` as UserName,
      GROUP_CONCAT(c.`Name`) as FriendsList
FROM users a LEFT JOIN friends b on a.uid = b.uid
    LEFT JOIN users c on b.fid = c.uid
GROUP BY a.uid

答案 2 :(得分:2)

这应该可以通过单个易于索引的查询来完成;

SELECT name FROM users u
JOIN friends f 
  ON u.uid = f.uid OR u.uid = f.fid
WHERE (f.uid=1 OR f.fid=1) 
  AND u.uid<>1;

演示here

答案 3 :(得分:1)

prequel question一样,您需要覆盖用户表的两个外键以获取所有朋友:

SELECT users.*
FROM  (
    SELECT uid FROM friends WHERE fid = 1
    UNION ALL
    SELECT fid FROM friends WHERE uid = 1
    ) f
JOIN   users USING (uid)

答案 4 :(得分:0)

在您的查询中切换朋友和用户我认为您将得到您想要的内容。

换句话说:

SELECT name FROM friends LEFT JOIN users ON friends.uid=users.uid WHERE friends.uid='1' OR friends.fid='1'

答案 5 :(得分:0)

我认为这是正确的SELECT name FROM users LEFT JOIN friends ON friends.uid=users.uid WHERE friends.uid=1 OR friends.fid=1