对等值列的结果进行分组和限制

时间:2015-02-19 16:33:29

标签: mysql

有这样一张桌子:

| col1 | col2 |
---------------
|  1   |  a   |
|  2   |  b   |
|  3   |  a   |
|  4   |  a   |
|  5   |  a   |
|  6   |  b   |
|  7   |  a   |
|  8   |  b   |

我想随机选择包含ab的行,但将结果限制为每行ab的2行,如下所示:

| col1 | col2 |
---------------
|  3   |  a   |
|  5   |  a   |
|  2   |  b   |
|  8   |  b   |

我可能遗漏了一些东西,但我无法弄明白该怎么做。

2 个答案:

答案 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;