Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql query to select one specific row and another random row

Tags:

random

mysql

I want to display two records.

For eg select * FROM users WHERE user_id = 5.

Now i want another row randomly selected from users table but with user_id != 5

Is it possible to do in a single query. I tried using union all but i dnt get two distinct rows.

Thanks

like image 735
codingbbq Avatar asked Oct 18 '10 10:10

codingbbq


1 Answers

This works fine for me. The first result is always the record with ID 5, the second row is a random one. Note that if no record with the ID 5 exists, both rows will be random.

SELECT * FROM users ORDER BY (user_id = 5) DESC, RAND() LIMIT 0,2 
like image 141
Pekka Avatar answered Oct 14 '22 00:10

Pekka