6

Possible Duplicate:
Simple Random Samples from a (My)Sql database

Hi!

Let say that I have a table of users. I want a query that shuffle the result and only show 5 users. How do I do that in MySQL query without using any php?

Community
  • 1
  • 1
einstein
  • 13,389
  • 27
  • 80
  • 110

2 Answers2

12

You can use rand(), but the performance is terrible

select * from users order by rand() limit 5; <-- slow

I would suggest, store list of all user id into an serialize array and cache into a disk-file. (periodically update)

So, you can un-serialize it back using PHP, and use PHP array_rand to pick 5 random users.

To fetch the full information, you can do

select * from users where user_id in(...); <-- very fast
ajreal
  • 46,720
  • 11
  • 89
  • 119
1
SELECT user FROM users
ORDER BY RAND()
LIMIT 5
Amjad Masad
  • 4,035
  • 1
  • 21
  • 20