显示mysql随机结果 [英] Show mysql random result

查看:102
本文介绍了显示mysql随机结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为events的mysql表.一些事件是特色.我想随机显示两个最新的特色事件之一. 时间戳"字段保存事件创建时间的UNIX时间戳.

I have a mysql table named events. Some events are featured. I want to randomly display one of the two latest featured events. The field 'timestamp' holds the UNIX timestamp of the event's creation time.

查询现在看起来像这样:

The query looks like this now:

$query = "SELECT * FROM events WHERE featured = 1 ORDER BY timestamp DESC LIMIT 2;";

有没有一种方法可以使查询语法化,以仅返回这两个事件之一并立即显示它,还是应该使用php来解决它?

Is there a way to syntax the query to return just one of those two events and display it right away, or should I go around it with php?

这里推荐什么?

推荐答案

根据

Use a ORDER BY RAND() LIMIT 1;, as per MySQL documentation for RAND() (near the bottom of the explanation). I'm not sure if you can do it without the nesting, but it shouldn't be all that expensive given that your nested table only has 2 rows.

SELECT * FROM 
    (SELECT * FROM events WHERE featured = 1 ORDER BY timestamp DESC LIMIT 2) 
ORDER BY RAND() LIMIT 1;

这篇关于显示mysql随机结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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