我有一个示例数据:
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),如何修复呢?
答案 0 :(得分:0)
试试这个..把RAND放在where子句中不在ORDER BY ...
SELECT p.id,p.name,p.category_id FROM
test
AS p WHERE(SELECT count(*)FROMtest
f WHERE f.category_id = p.category_id AND f.id&lt; = p.id)&lt; = 2 AND RAND()&lt; = 6