如何RANDOM()在SQL中选择每组的第一个/最小/ ...行?

时间:2012-10-01 07:22:03

标签: php mysql

我有一个示例数据:

id|category_id|name
--------------
1|1|test 1
2|1|test 2
3|1|test 3
4|2|test 4
5|2|test 5
6|2|test 6

和mysql

SELECT p.id, p.name, p.category_id 
FROM `test` AS p 
WHERE (SELECT count(*) FROM `test` f WHERE f.category_id = p.category_id AND f.id <= p.id) <= 2 
ORDER BY RAND()

结果是:

1|1|test 1
2|1|test 2
4|2|test 4
5|2|test 5

=&GT;但是结果不能RANDOM()值来获取其他值(id = 3和id = 6),如何修复呢?

1 个答案:

答案 0 :(得分:0)

试试这个..把RAND放在where子句中不在ORDER BY ...

  

SELECT p.id,p.name,p.category_id FROM test AS p WHERE(SELECT   count(*)FROM test f WHERE f.category_id = p.category_id AND f.id&lt; =   p.id)&lt; = 2 AND RAND()&lt; = 6