mysql query to select one specific row and another random row

℡╲_俬逩灬. 提交于 2020-01-12 19:29:21

问题


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


回答1:


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 



回答2:


Try this

SELECT * FROM users WHERE user_id = 5 || user_id != 5 ORDER BY RAND() LIMIT 2



回答3:


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)



回答4:


Try this:

SELECT * FROM users WHERE user_id=5
union all (
  SELECT * FROM  users WHERE user_id!=5
  ORDER BY RAND() LIMIT 0,1)


来源:https://stackoverflow.com/questions/3958366/mysql-query-to-select-one-specific-row-and-another-random-row

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!