2011-04-12 114 views
0

我試圖返回兩個用戶之間的第一條消息,無論我是發送該消息還是收到它。我編寫了下面的查詢,它返回所有正確的線程,但似乎忽略了DISTINCT子句 - 最後我得到了多個具有相同'someid'的結果。SELECT DISTINCT在CASE語句後不工作

如何糾正此查詢,以便在結果'someid'列中不會有重複值返回?

這裏就是我目前使用:

SELECT DISTINCT CASE WHEN $userid != senderid THEN senderid ELSE GROUP_CONCAT(receivers.id SEPARATOR ', ') END someid, 
      CASE WHEN $userid != senderid THEN senders.username ELSE GROUP_CONCAT(receivers.username SEPARATOR ', ') END somename, 
      messages.body, 
      messages.time 
    FROM messages 
    LEFT JOIN messages_recipients AS recipients ON messages.id = recipients.messageid 
    LEFT JOIN users AS senders ON messages.senderid = senders.id 
    LEFT JOIN users AS receivers ON recipients.userid = receivers.id 
    WHERE recipients.userid = $userid 
    OR messages.senderid = $userid 
    GROUP BY messages.id 
    ORDER BY messages.time DESC 
+0

我想你將不得不闖入2個查詢,內部執行SomeId上的Distinct ... – 2011-04-13 00:10:23

+0

我會在哪裏放置該查詢? – Walker 2011-04-13 01:28:00

回答

2

正如@米奇小麥提到的,你可能有到DISTINCT分成外部查詢。

SELECT DISTINCT * FROM 
    (
    SELECT CASE WHEN ... GROUP BY messages.id ORDER BY messages.time DESC 
    ) AS inner_q 
ORDER BY messages.time DESC 

但請記住,DISTINCT是不同的記錄不是一個單一的值(someid)。 messages.time可能會阻止你得到你以後的東西。

+0

謝謝布倫特,有沒有辦法只返回someid = X的第一個結果? – Walker 2011-04-13 01:37:51

+0

正在尋找「AS inner_q」語法,感謝提醒我! – 2017-05-24 13:02:29