我如何将以下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;
答案 0 :(得分:6)
要将ORDER BY
或LIMIT
应用于个人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