mysql query to select one specific row and another

2019-04-07 15:56发布

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

标签: mysql random
4条回答
甜甜的少女心
2楼-- · 2019-04-07 16:35

Try this

SELECT * FROM users WHERE user_id = 5 || user_id != 5 ORDER BY RAND() LIMIT 2
查看更多
冷血范
3楼-- · 2019-04-07 16:39

Try this:

SELECT * FROM users WHERE user_id=5
union all (
  SELECT * FROM  users WHERE user_id!=5
  ORDER BY RAND() LIMIT 0,1)
查看更多
Deceive 欺骗
4楼-- · 2019-04-07 16:40

Union should do the trick. You probably forgot LIMIT.

(SELECT * FROM users WHERE user_id = 5 LIMIT 1)
UNION
(SELECT * FROM users WHERE user_id != 5 LIMIT 1)
查看更多
Root(大扎)
5楼-- · 2019-04-07 16:46

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 
查看更多
登录 后发表回答