2014-09-11 89 views
1

根據我對連接工作原理的瞭解,它會創建儘可能多的組合。如果該值不存在,則左連接可以創建與null的組合。我遇到的問題是以下朋友和贈送系統。當結果可能或可能不在表中時左連接

  • 用戶#2的朋友3和4
  • 用戶#2的禮物已經在那裏爲用戶3
  • 用戶#2對#4

當我運行沒有禮物在下面的查詢中,只能找到2個情況中的一個到#4的友誼。表中沒有禮物,在這種情況下,它返回帶有NULL值的禮物值的朋友,或者每個朋友至少有一個禮物。我需要做的是返回每一位朋友和他們最後的禮物,或者如果他們從未給出過,則返回null。

表結構:

  • 用戶 - >用戶提供名稱的列表
  • FRIENDS->(1個用戶是友好的始發和另一個是目的地2個用戶之間的關係的列表)
  • 工藝 - >從一個用戶向另一

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 
禮品列表
+0

讓你從所有用戶(除2),朋友們需要記錄所有可能的組合(與發端= 2)和禮品(含始發= 2),然後過濾,留下只是'gifts.destination =用戶的那些.name'?至於我這沒有什麼意義 – 2014-09-11 06:56:45

回答

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 

希望這是你所需要的。

+0

我不得不調整一些外圍條款,但整體改變到左連接似乎已經完成了。我會再次發佈,如果我發現任何角落案件,這不起作用。謝謝! – user2292539 2014-09-11 06:52:56