我有以下 MYSQL 查询:
SELECT m.id AS id, 'admin' AS type, m.title AS title, m.message AS message, m.link AS link, m.image AS image, 'White' AS colour_scheme
FROM x_elder_messages m
UNION
SELECT a.id AS id, 'evidence' AS type, a.name AS title, a.about AS message, CONCAT('http://www.aaa.com/x/view/ambition/',a.id,'/') AS link, CONCAT('http://www.aaa.com/x/x_images/x_ambitions/current/thumb/',ai.image_id,'.jpg') AS image, 'White' AS colour_scheme
FROM x_ambitions a
INNER JOIN x_ambition_images ai
ON a.id = ai.ambition_id
UNION
SELECT u.id AS id, 'profile_update' AS type, CONCAT(u.x_first_name,' ',u.x_last_name) AS title, CONCAT(CONCAT(u.x_first_name,' ',u.x_last_name),' has recently updated their profile') AS message, CONCAT('http://www.aaa.com/x/view/',u.id,'/') AS link, CONCAT('http://www.aaa.com/x/x_images/x_users/current/thumb/',i.image_id,'.jpg') AS image, 'Dark' AS colour_scheme
FROM x_user u
INNER JOIN x_user_images i
ON u.id = i.user_id
ORDER BY RAND()
我让输出具有相同的列名,这样我就可以将结果作为一个整体来处理。但是有什么方法可以限制每个查询的数量为 2,以便它可以获取 2 个管理员、2 个目标和 2 个用户?
谢谢
最佳答案
是的,你可以在每个子查询中放置一个limit
:
(SELECT m.id AS id, 'admin' AS type, m.title AS title, m.message AS message, m.link AS link, m.image AS image, 'White' AS colour_scheme
FROM x_elder_messages m
LIMIT 2
) UNION
(SELECT a.id AS id, 'evidence' AS type, a.name AS title, a.about AS message, CONCAT('http://www.aaa.com/x/view/ambition/',a.id,'/') AS link, CONCAT('http://www.aaa.com/x/x_images/x_ambitions/current/thumb/',ai.image_id,'.jpg') AS image, 'White' AS colour_scheme
FROM x_ambitions a
INNER JOIN x_ambition_images ai
ON a.id = ai.ambition_id
LIMIT 2
) UNION
(SELECT u.id AS id, 'profile_update' AS type, CONCAT(u.x_first_name,' ',u.x_last_name) AS title, CONCAT(CONCAT(u.x_first_name,' ',u.x_last_name),' has recently updated their profile') AS message, CONCAT('http://www.aaa.com/x/view/',u.id,'/') AS link, CONCAT('http://www.aaa.com/x/x_images/x_users/current/thumb/',i.image_id,'.jpg') AS image, 'Dark' AS colour_scheme
FROM x_user u
INNER JOIN x_user_images i
ON u.id = i.user_id
LIMIT 2
)
ORDER BY RAND() ;
此外,您应该使用union all
,除非您想有意删除重复项(这会增加额外的处理)。当使用 limit
时,您通常需要一个 order by
来指定您获得的行数。
关于mysql - 有没有办法从每个查询中获取 2 行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21431132/