Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/72.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/8/visual-studio-code/3.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
如何在像linkedin这样的mysql中找到用户的二级连接?_Mysql_Self Join - Fatal编程技术网

如何在像linkedin这样的mysql中找到用户的二级连接?

如何在像linkedin这样的mysql中找到用户的二级连接?,mysql,self-join,Mysql,Self Join,我需要编写一个查询来获取用户的二级连接 假设有四个朋友:A、B、C、D A is friend with B B is friend with C and D 现在我想找到A,e,C和D的二级连接 数据库设计 表:用户 id name 1 A 2 B 3 C 4 D 表:用户朋友 id friend1 friend2 1 1 2 2 2 3 3 2 4 有人帮我查询吗?这可以: SELECT f.name FROM

我需要编写一个查询来获取用户的二级连接

假设有四个朋友:A、B、C、D

A is friend with B
B is friend with C and D
现在我想找到A,e,C和D的二级连接

数据库设计

表:用户

id name
1  A
2  B
3  C
4  D 
表:用户朋友

id  friend1  friend2
1    1        2
2    2        3
3    2        4
有人帮我查询吗?

这可以:

SELECT f.name
FROM users AS u, user_friends AS a, user_friends AS b, users as f
WHERE u.name='A' AND u.id != f.id AND
  ((u.id = a.friend1 AND a.friend2 = b.friend1 AND b.friend2 = f.id) OR
   (u.id = a.friend1 AND a.friend2 = b.friend2 AND b.friend1 = f.id) OR
   (u.id = a.friend2 AND a.friend1 = b.friend1 AND b.friend2 = f.id) OR
   (u.id = a.friend2 AND a.friend1 = b.friend2 AND b.friend1 = f.id));

谢谢:)。还有别的办法解决吗?实际上有人在面试中问过我这个问题。哈哈。几乎总是有其他的方法来解决它。这种情况也不例外。