LIMIT和UNION ALL不返回请求的记录数

时间:2015-08-04 16:06:44

标签: mysql sql

我有一个包含多个type值的表,我想从其中一些获取样本记录。

我目前的查询如下:

-- Pulling three sample records from each "type"
SELECT * FROM example WHERE type = "A" LIMIT 3
UNION ALL
SELECT * FROM example WHERE type = "B" LIMIT 3
UNION ALL
SELECT * FROM example WHERE type = "C" LIMIT 3
;

我希望这能够共返回9条记录; 3来自type = "A",3来自type = "B",3来自type = "C"

但是,我实际收到的结果是来自type = "A" 的3条记录,而没有其他
我知道其他type值存在,因为我可以运行单个SELECT语句并返回结果。

为什么MySQL只返回3条记录,如何让它返回我想要的全部9条记录?

我创建了一个SQL小提琴来说明问题:http://sqlfiddle.com/#!9/d911c/2

3 个答案:

答案 0 :(得分:3)

使用括号:

(SELECT * FROM example WHERE type = "A" LIMIT 3)
UNION ALL
(SELECT * FROM example WHERE type = "B" LIMIT 3)
UNION ALL
(SELECT * FROM example WHERE type = "C" LIMIT 3);

Demo here

manual

中记录了这一点
  

要将ORDER BY或LIMIT应用于单个SELECT,请放置该子句   在括起SELECT的括号内:

     

(选择一个FROM t1,其中a = 10和B = 1,按极限10排序)UNION   (选择一个FROM t2 WHERE a = 11 AND B = 2 ORDER by LIMIT 10);

答案 1 :(得分:2)

在选择

周围加上括号
(SELECT * FROM example WHERE type = "A" LIMIT 3)
UNION ALL
(SELECT * FROM example WHERE type = "B" LIMIT 3)
UNION ALL
(SELECT * FROM example WHERE type = "C" LIMIT 3)

SQLFiddle

答案 2 :(得分:0)

限制适用于所有行,而不仅仅是每个部分。即您在所有查询中设置的限制为3,而不是每个部分。因此,为了对每个部分应用限制,您需要对其进行子查询:

SELECT * FROM (select * from example WHERE type = "A" LIMIT 3) tbl1
UNION ALL
SELECT * FROM (select * from example WHERE type = "B" LIMIT 3) tbl2
UNION ALL
SELECT * FROM (select * from example WHERE type = "C" LIMIT 3) tbl3
;

这应该会给你你正在寻找的结果