MySQL: shuffle the result of a limited query?

Possible duplicate:
Simple random samples from (My) Sql database

Hello!

Say I have a user table. I need a query that shuffles the result and displays only 5 users. How to do this in a MySQL query without using php?

+4
source share
2 answers

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

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

I would suggest saving a list of all user identifiers in a serialization array and cache it in a disk file. (update periodically)

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

To get the full information, you can do

 select * from users where user_id in(...); <-- very fast 
+11
source
 SELECT user FROM users ORDER BY RAND() LIMIT 5 
0
source

Source: https://habr.com/ru/post/1333400/


All Articles