mysql - 有没有办法从每个查询中获取 2 行?

标签 mysql select limit inner-join union

我有以下 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/

相关文章:

mysql - 数据库错误(MySQL)

php - 在php和mysql中创建多维数组

sql - 如何重用 2 个相同子查询检索到的值?

php - 当我检查一行时,为什么 MySQL 没有在 LIMIT 1 处停止?

hadoop - hadoop 中超过 120 个计数器

android - 在视频库 android 中显示小于 5 MB 的视频文件

MySql表如何获取所有联系人?

python - 用 FK 查找替换列表理解

mysql - SELECT DISTINCT 数据不同但未被过滤

sql - 在 Where 子句中添加检查参数是否为空字符串