Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql “;朋友”;关系(2个表)_Sql_Database - Fatal编程技术网

Sql “;朋友”;关系(2个表)

Sql “;朋友”;关系(2个表),sql,database,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

我有两张这样的桌子

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');

在这里,您需要为每个
user\u a
user\u b
加入用户表两次:

请尝试以下查询:

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   ║
╚══════╝
看见
编辑:在查询(您已经尝试过)中,您在子查询中使用了外部表的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');
请参见以下内容:

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';

您正在使用哪些RDBMS?
`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