我想知道 MySQL 中是否有一种方法可以为每个 OR 限制 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
了,但这就是我能想到的(但它没有用)。在此先感谢,马修
问问题
99 次
2 回答
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
于 2012-06-28T01:11:27.697 回答
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)
于 2012-06-28T01:11:18.777 回答