简体   繁体   中英

How to RANDOM() select the first/least/… row per group in SQL?

I have a sample data:

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

And 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()

And result is:

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

=> But result can't RANDOM() value to get other value(id=3 and id=6), how to fix it ?

try this.. put the RAND in where clause not in 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 <= p.id) <= 2 AND RAND() <= 6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM