1

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 ?

2
  • What are the first/least/max rows you want to get from the sample data you posted? add them please. Oct 1, 2012 at 7:33
  • @MahmoudGamal: how to random result all id Oct 1, 2012 at 7:36

1 Answer 1

0

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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.