MySQL查询选择一个特定的行和另一随机行 [英] mysql query to select one specific row and another random row

查看:80
本文介绍了MySQL查询选择一个特定的行和另一随机行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想显示两个记录.

例如 select * FROM users WHERE user_id = 5.

现在,我要从用户表中随机选择另一行,但要使用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.

谢谢

推荐答案

这对我来说很好.第一个结果始终是ID为5的记录,第二行为随机记录.请注意,如果不存在ID为5的记录,则两行都是随机的.

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 

这篇关于MySQL查询选择一个特定的行和另一随机行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆