MySQL限制为OR

时间:2012-06-28 01:08:58

标签: mysql

我想知道在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但这就是我能想到的全部(而且它没有用)。 提前致谢, 马修

2 个答案:

答案 0 :(得分: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如何确定您想要的行。


<强>更新

要获取每个用户的最新帖子,请将结果集从最新到最旧订购:

(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

答案 1 :(得分:0)

如何使用union?

感谢@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)