有这样一张桌子:
| col1 | col2 |
---------------
| 1 | a |
| 2 | b |
| 3 | a |
| 4 | a |
| 5 | a |
| 6 | b |
| 7 | a |
| 8 | b |
我想随机选择包含a
和b
的行,但将结果限制为每行a
和b
的2行,如下所示:
| col1 | col2 |
---------------
| 3 | a |
| 5 | a |
| 2 | b |
| 8 | b |
我可能遗漏了一些东西,但我无法弄明白该怎么做。
答案 0 :(得分:0)
这就是你想要的吗?
select * from yourTable where col2 = 'a' order by rand() limit 2
union all
select * from yourTable where col2 = 'b' order by rand() limit 2;
答案 1 :(得分:0)
您还需要使用ORDER BY RAND()
:
select * from yourTable where col2 = 'a' order by rand() limit 2
union
select * from yourTable where col2 = 'b' order by rand() limit 2;