“朋友”关系(2桌)

时间:2013-05-25 10:13:48

标签: sql database

我有两张这样的表

Users table
id    | name
-------------
1     |  s1
2     |  s2
3     |  s3
4     |  s4
5     |  s5
6     |  s6



friends table
friendID | user_a | user_b
--------------------
1        |   1    |   2
2        |   3    |   1
3        |   4    |   2
4        |   1    |   3

我想运行此查询:谁是s1的朋友?
这是我当前的查询,但它不起作用

select a.name
from users a, friends b
where a.id=b.user_b
and b.user_a = (select b.user_a
               from friends
               where a.name='s1');

3 个答案:

答案 0 :(得分:3)

在这里,您需要为每个user_auser_b加入Users表两次:

尝试此查询:

SELECT u.name
  FROM Users u 
  JOIN friends f
    ON u.id = f.user_b
  JOIN Users u1
    ON u1.id = f.user_a
 WHERE u1.name = 's1';

结果:

╔══════╗
║ NAME ║
╠══════╣
║ s2   ║
║ s3   ║
╚══════╝

请参阅this SQLFiddle


编辑:在您的查询中(您已尝试过),您在子查询中使用了外部表的ID和名称。所以你需要像这样使用子表的id和名称:

select a.name
from users a, friends b
where a.id=b.user_b
and b.user_a IN (select id
                 from users
                 where name='s1');

请参阅this SQLFiddle

答案 1 :(得分:1)

请试试这个:

SELECT DISTINCT c.name
FROM users a, friends b, users c
WHERE a.id=b.user_a
    AND b.user_b=c.id
    AND a.name='s1';

答案 2 :(得分:0)

`SELECT DISTINCT users.name 
FROM users, friends
WHERE (users.id=friends.user_a OR users.id=friends.user_b )
      AND (friends.user_a='1' OR friends.user_b='1')
      AND (users.id!='1')`                                                                              

Result:

s2
s3