gpt4 book ai didi

mysql - SQL:返回访问过同一个地方的用户列表

转载 作者:太空宇宙 更新时间:2023-11-03 11:57:53 25 4
gpt4 key购买 nike

给定一个特定的用户 x,我想找出其他用户访问过该用户去过的所有地方。为此,我认为我需要查询同一个表两次并执行连接以查找匹配的记录,但到目前为止我还没有运气。

考虑以下简化的表结构:

----- VISITATION -----
visitationId PK
placeId FK <-- The place that was visited
userId FK <-- The user who visited this place

我不需要从这些外部表中提取任何信息,现在我只需要一个与用户 x

访问过同一地点的用户 ID 的列表
----- RESULT -----
placeId userId
1 2
1 3
1 1
4 1
4 5
5 8

如果我以用户 1 的身份登录,我希望返回用户 2、3 和 5,而不会返回 8,因为他在特定位置与 1 没有关系。

为了解决这个问题,我尝试了以下查询:

SELECT x.userId, 
y.userId
FROM visitation x
JOIN
visitation y
ON
y.placeId = x.placeId
WHERE
x.userId = 1
GROUP
BY x.userId

目前这只返回 1,我将如何返回共享该位置的所有用户?

最佳答案

这是一个方法。您可以在 placeid 上加入,然后确保所有匹配:

select vy.userid
from visitation vx left join
visitation vy
on vx.placeid = vy.placeid and vx.userid <> vy.userid
where vx.userid = 1
group by vy.userid
having count(*) = count(vy.placeid);

关于mysql - SQL:返回访问过同一个地方的用户列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31247713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com