sql 不同连接

发布于 2024-12-17 19:28:55 字数 579 浏览 1 评论 0原文

表:

  • 活动:id,userId,描述,objectId
  • 用户:id,名称
  • usersFriends,id,userId,friendUserId
  • 对象:id,名称

当前查询:

   SELECT A.*, U.*
   FROM usersFriends UF
   JOIN activities A ON A.userId = UF.friendUserId
   JOIN users U ON U.id = A.userId
   WHERE A.objectId = x

当前查询的问题是,如果用户有匹配的好友 例如:

  • user 1 : tim
  • 用户 2: ryan
  • 用户 3: allan
  • 用户 4: charlie

tim 是 charlie 的朋友 瑞安是查理的朋友

我们得到了对象X的活动,但是我们得到了所有活动的两倍,因为蒂姆是查理的朋友而瑞安是查理的朋友,所以我需要某种不同的?

感谢您的帮助!

Table:

  • activities: id, userId, description, objectId
  • users: id, name
  • usersFriends, id, userId, friendUserId
  • objects: id, name

The current query:

   SELECT A.*, U.*
   FROM usersFriends UF
   JOIN activities A ON A.userId = UF.friendUserId
   JOIN users U ON U.id = A.userId
   WHERE A.objectId = x

The problem with the current query is that if users have matching friends for example:

  • user 1: tim
  • user 2: ryan
  • user 3: allan
  • user 4: charlie

tim is friends with charlie
ryan is friends with charlie

We get the activities of object X, but we get all the activities double because tim is friends with charlie and ryan is friends with charlie, so I need some kind of distinct?

Thanks for help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浮生未歇 2024-12-24 19:28:55

我通常喜欢这个 ... AND A.userId < UF.userId

SELECT A.*, U.*
   FROM usersFriends UF
   JOIN activities A ON A.userId = UF.friendUserId AND A.userId < UF.userId
   JOIN users U ON U.id = A.userId
   WHERE A.objectId = x

I usually do like this ... AND A.userId < UF.userId

SELECT A.*, U.*
   FROM usersFriends UF
   JOIN activities A ON A.userId = UF.friendUserId AND A.userId < UF.userId
   JOIN users U ON U.id = A.userId
   WHERE A.objectId = x
淡水深流 2024-12-24 19:28:55

好吧,看来你可以执行以下查询(尽管我不太理解逻辑):

SELECT A.*, U.*
FROM (SELECT DISTINCT friendUserId FROM usersFriends) UF
JOIN activities A ON A.userId = UF.friendUserId
JOIN users U ON U.id = A.userId
WHERE A.objectId = x

或者

SELECT DISTINCT A.*, U.*
FROM usersFriends UF
JOIN activities A ON A.userId = UF.friendUserId
JOIN users U ON U.id = A.userId
WHERE A.objectId = x

Well, it seems that you can do the following query (though I don't really understand the logic ):

SELECT A.*, U.*
FROM (SELECT DISTINCT friendUserId FROM usersFriends) UF
JOIN activities A ON A.userId = UF.friendUserId
JOIN users U ON U.id = A.userId
WHERE A.objectId = x

Or

SELECT DISTINCT A.*, U.*
FROM usersFriends UF
JOIN activities A ON A.userId = UF.friendUserId
JOIN users U ON U.id = A.userId
WHERE A.objectId = x
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文