垂直堆栈MySQL导致单个查询

时间:2012-04-02 20:09:51

标签: mysql

我如何将以下3个查询组合(垂直堆叠)到一个查询,返回100行,类别1中的50行,来自类别2的25个,来自类别3的25个,都是随机选择的。我试过UNION但似乎没有用。

select * from table where category_id = 1 order by rand() limit 50;

select * from table where category_id = 2 order by rand() limit 25;

select * from table where category_id = 3 order by rand() limit 25;

2 个答案:

答案 0 :(得分:6)

要将ORDER BYLIMIT应用于个人SELECT,请将该子句放在括起SELECT的括号内:

(select * from table where category_id = 1 order by rand() limit 50)
UNION ALL
(select * from table where category_id = 2 order by rand() limit 25)
UNION ALL
(select * from table where category_id = 3 order by rand() limit 25);

答案 1 :(得分:3)

您正在寻找的是UNION ALL语法(链接到MySQL文档)。

select * from table where category_id = 1 order by rand() limit 50
UNION ALL
select * from table where category_id = 2 order by rand() limit 25
UNION ALL
select * from table where category_id = 3 order by rand() limit 25;

编辑:删除分号,谢谢@Matt Fenwick