以下是我的数据库架构:
id | user1 | user2 | status //status 1 means the user is a friend
1 1 2 1
2 3 1 1
3 1 4 1
4 2 3 1
5 4 2 1
在上面的例子中
我需要找到两个人之间的共同朋友。
任何想法,
答案 0 :(得分:1)
我不确定这是否是最佳解决方案。但也许是这样的:
SELECT
*
FROM
(
SELECT
CASE WHEN t2.user1=1 THEN t2.user2 ELSE t2.user1 END AS userId
FROM
t AS t2
WHERE 1 IN (t2.user1,t2.user2)
AND t2.[status]=1
) as tbl
WHERE EXISTS
(
SELECT
NULL
FROM
t
WHERE 2 IN (t.user1,t.user2)
AND tbl.userId=(CASE WHEN t.user1=2 THEN t.user2 ELSE t.user1 END)
AND t.[status]=1
)
这得到了来自用户1和2的共同朋友。这是3,4
答案 1 :(得分:0)
据我所知,此查询应该足够了。 其中{x}是userA,{y}是userB
select user2
from friends
where user1 = {x}
and status = 1
and user2 in (
select user2
from friends
where user1 = {y}
and status = 1
)