当我运行此查询时:
SELECT 1, `name` FROM `table1` WHERE `reg` = 3 AND `lang` = 5
UNION
SELECT 2, `name` FROM `table1` WHERE `reg` = 1 AND `lang` = 2
UNION
SELECT 3, `name` FROM `table1` WHERE `reg` = 6 AND `lang` = 10
返回:Showing rows 0 - 24 (435 total, Query took 0.0110 sec)
我需要使用LIMIT 5
运行这些查询,因此我必须在每个select
周围使用括号,在这种情况下使用括号和限制:
(SELECT 1, `name` FROM `table1` WHERE `reg` = 3 AND `lang` = 5 LIMIT 5)
UNION
(SELECT 2, `name` FROM `table1` WHERE `reg` = 1 AND `lang` = 2 LIMIT 5)
UNION
(SELECT 3, `name` FROM `table1` WHERE `reg` = 6 AND `lang` = 10 LIMIT 5)
返回以下内容:Showing rows 0 - 24 (17098 total, 0 in query, Query took 0.0020 sec)
我做错了吗?
答案 0 :(得分:1)
您的第二个查询与第一个查询不同,因为您在第二个查询中使用 LIMIT 5
修改: - 强>
你可以试试这个:
(SELECT 1 as sort_col, `name` FROM `table1` WHERE `reg` = 3 AND `lang` = 5 LIMIT 5)
UNION
(SELECT 2, `name` FROM `table1` WHERE `reg` = 1 AND `lang` = 2 LIMIT 5)
UNION
(SELECT 3, `name` FROM `table1` WHERE `reg` = 6 AND `lang` = 10 LIMIT 5)
ORDER BY sort_col, `name`
来自MYSQL Docs:
使用ORDER BY或LIMIT子句对整个UNION进行排序或限制 结果,括起单个SELECT语句并放置 最后一个之后的ORDER BY或LIMIT。
答案 1 :(得分:0)
使用括号更改查询的处理,为每个子查询分配优先级
调查两个查询的使用Explain YOUR_QUERY
。