2012-06-28 89 views
0

我想知道是否有一種方法在MySQL中,比如每個OR的LIMIT 1。正如在,如果我有一個MySQL聲明SELECT * FROM posts WHERE username = 'Johnny' OR username = 'Matthew' OR username = 'Andy' OR username = 'Sandra' ORDER BY date DESC,但我想從每個用戶名(或在這種情況下,每個人的最新帖子)返回只有一個結果。我試過SELECT * FROM posts WHERE (username = 'Johnny' LIMIT 1) OR (username = 'Matthew' LIMIT 1) OR (username = 'Andy' LIMIT 1) OR (username = 'Sandra' LIMIT 1) ORDER BY date DESC,但這只是我能想到的一切(而且它不起作用)。 在此先感謝, 馬修MySQL限制或OR

回答

2

您可以使用UNION到單獨的查詢組合:

(SELECT * FROM posts WHERE username = 'Johnny' LIMIT 1) 
UNION ALL 
(SELECT * FROM posts WHERE username = 'Matthew' LIMIT 1) 
UNION ALL 
(SELECT * FROM posts WHERE username = 'Andy' LIMIT 1) 
UNION ALL 
(SELECT * FROM posts WHERE username = 'Sandra' LIMIT 1) 

或者,您可以將結果通過用戶名:

SELECT * 
FROM  posts 
WHERE username IN ('Johnny','Matthew','Andy','Sandra') 
GROUP BY username 

上面給出的這兩個查詢都將爲每個返回不確定的行用戶(可能或可能不是你所需要的)。要獲取特定的行,請指定MySQL如何確定您想要的行。


UPDATE

爲了獲取最新的針對每個用戶的帖子,並下令從最新到最舊的結果集:

(SELECT * FROM posts WHERE username = 'Johnny' ORDER BY date DESC LIMIT 1) 
UNION ALL 
(SELECT * FROM posts WHERE username = 'Matthew' ORDER BY date DESC LIMIT 1) 
UNION ALL 
(SELECT * FROM posts WHERE username = 'Andy' ORDER BY date DESC LIMIT 1) 
UNION ALL 
(SELECT * FROM posts WHERE username = 'Sandra' ORDER BY date DESC LIMIT 1) 
ORDER BY date DESC 

和:

SELECT * 
FROM  posts NATURAL JOIN (
      SELECT username, MAX(date) AS date 
      FROM  posts 
      WHERE username IN ('Johnny','Matthew','Andy','Sandra') 
      GROUP BY username 
     ) AS t 
GROUP BY username -- only required if multiple posts might have the same date 
ORDER BY date DESC 
+0

這裏使用的UNION ALL和下面使用的UNION有什麼區別?另外,我該如何做'ORDER BY date DESC'?謝謝:D – MatthewSot

+0

@IMAPC:'UNION'的默認行爲是將重複的行從結果中刪除,可選的'DISTINCT'關鍵字不起作用除了缺省值,因爲它也指定了刪除重複行。使用可選的'ALL'關鍵字,重複行刪除不會發生,結果包括所有'SELECT'語句中的所有匹配行。「因此,添加'ALL'如果你不需要MySQL來掃描和刪除重複項,效率更高(這裏就是這種情況,因爲重複項是不可能的) – eggyal

+0

@IMAPC:當你說你希望'按ORDER BY date DESC',你意味着您希望每個用戶的最新帖子以任意順序返回,或者您希望每個用戶的帖子按降序排列的順序返回?或者兩者兼得:您希望每個用戶的最新帖子以遞減日期順序返回? – eggyal

0

如何使用聯合?

與感謝@eggyal校正編輯:

(SELECT * FROM posts WHERE username = 'Johnny' LIMIT 1) 
UNION 
(SELECT * FROM posts WHERE username = 'Matthew' LIMIT 1) 
UNION 
(SELECT * FROM posts WHERE username = 'Andy' LIMIT 1) 
+2

項記載[手冊](http://dev.mysql.com/doc/en/union.html):「應用'ORDER BY'或'L IMIT「添加到單個的」SELECT「中,將該子句放在括號內的括號中。 – eggyal

+0

但如果我想要排序所有結果(如所有不同的SELECT中的結果),該怎麼辦?我應該在最後加上'ORDER BY date DESC')嗎? – MatthewSot

+0

對不起,這是在你鏈接的手冊中,也許我應該在下一次閱讀它之前詢問(: – MatthewSot