sql distinct join

时间:2011-11-25 18:27:09

标签: sql distinct

表:

  • 活动:id,userId,description,objectId
  • 用户:id,name
  • usersFriends,id,userId,friendUserId
  • 对象:id,name

当前查询:

   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

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

  • 用户1:tim
  • 用户2:ryan
  • 用户3:allan
  • 用户4:查理
蒂姆是查理的朋友 瑞安是查理的朋友

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

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

好吧,似乎你可以做以下查询(虽然我真的不了解逻辑):

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

答案 1 :(得分:0)

我通常喜欢这个... 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