当结果可能会或可能不在表格中时,左联接

时间:2014-09-11 06:37:30

标签: mysql

根据我对连接如何工作的理解,它可以创建尽可能多的组合。如果值不存在,则左连接可以创建带有null的组合。我遇到的问题是以下朋友和送礼系统。

  • 用户#2有朋友3和4
  • 用户#2已经为用户3提供了礼物
  • 用户#2没有#4
  • 的礼物

当我运行以下查询时,它只能在2个案例中的一个中找到#4的友谊。表中没有礼物,在这种情况下,它返回两个朋友的礼物值为NULL,或者每个朋友至少有一个礼物。我需要它做的是将每个朋友和他们的最后一份礼物一起退还给他们,如果他们从未给过它们,则返回null。

表格结构:

  • 用户 - >名称为
  • 的用户列表
  • FRIENDS-> 2个用户之间的关系列表(1个用户是友谊的发起者,另一个是目的地)
  • 工艺 - >从一个用户到另一个用户的礼物列表

SELECT * 
FROM users
JOIN friends ON (friends.originator = 2 OR friends.destination = 2)// Find the friendships I am in
LEFT JOIN gifts ON (gifts.originator = 2)//Find all gifts where I sent the gift
WHERE users.name != 2 // filter out the users who are not me
and (gifts.originator IS NULL OR gifts.destination = users.name)//allow null gifts or gifts to the mentioned users
GROUP BY gifts.destination // show 1 gift per friend
ORDER BY gifts.time ASC//show only the latest gift

1 个答案:

答案 0 :(得分:0)

尝试:

SELECT * 
FROM users
JOIN friends ON (friends.originator = 2 OR friends.destination = 2)// Find the friendships I am in
LEFT JOIN gifts ON friends.originator = gifts.originator and gifts.destination = users.name) //Find all gifts where I sent the gift
WHERE users.name != 2 // filter out the users who are not me
GROUP BY gifts.destination // show 1 gift per friend
ORDER BY gifts.time ASC//show only the latest gift

希望这就是你所需要的。

相关问题