0

我有两张桌子

用户:(id,姓名)

关系:(user_id,relation_id)

User_id 和 relation_id 都是表中的 id users

我想要的是恢复与特定用户成为朋友的所有用户。

这是我的 sql 命令:这不起作用:

SELECT *
FROM users
NATURAL JOIN relations
WHERE user_id IN (SELECT id FROM users WHERE name='John doe');

你可以帮帮我吗?

4

7 回答 7

4
SELECT users.*
FROM relations
INNER JOIN users
  ON relations.relation_id = users.id
WHERE relations.user_id = 12345;

您还可以使用子查询获取 id,就像您在示例中所做的那样:

WHERE relations.user_id IN (SELECT id FROM users WHERE name='John doe');
于 2012-04-20T11:41:02.370 回答
2

要获取一个人拥有的所有关系,以下查询将起作用..

SELECT * FROM users us JOIN 关系 re ON us.id = re.relation_id WHERE re.user_id = ( SELECT id FROM users WHERE name = 'John doe' )

于 2012-04-20T11:56:45.547 回答
1

试试这个

SELECT * FROM users as a 
JOIN relations as b on a.id = b.user_id 
WHERE b.user_id IN (SELECT id FROM users WHERE name='John doe')
于 2012-04-20T11:39:05.183 回答
1
SELECT user_id
FROM relations re
JOIN users us
ON us.id = re.user_id
WHERE relation_id = (
    SELECT id
    FROM users
    WHERE name = 'John Doe'
)

旁注:您不能NATURAL JOIN在此处使用,因为在两个表中没有具有相同名称和类型的列。

于 2012-04-20T11:40:17.940 回答
1

这不只是通过您要查找的 userId 查询关系表的问题吗?

select * 
from relations
where  user_id = @IdYouArelookingFor or relation_id = @IdYouArelookingFor
于 2012-04-20T11:42:59.733 回答
1
SELECT friend.*
FROM users AS friend
  JOIN relations AS r
    ON r.relation_id = friend.id
  JOIN users AS u 
    ON u.id = r.user_id
WHERE u.name = 'John doe' ;
于 2012-04-20T11:45:53.360 回答
1

朋友是具有相同relation_id的人吗?

SELECT a.name FROM users a JOIN relations b on a.id = b.user_id
WHERE b.relation_id in 
(select relation_id from relations where id = 'userid of user you are looking for') 
AND a.id !=  'userid of user you are looking for'

如果您的逻辑不同,请告诉它是如何工作的

于 2012-04-20T11:48:56.700 回答