简体   繁体   English

PHP - Select 表中的随机行

[英]PHP - Select random row from table

My table has around 10k rows.我的表有大约 10k 行。 How can I query select 1 random row of the last 10 added rows?如何查询 select 最后 10 个添加行的 1 个随机行? I have a date column that is datetime of when the row was added.我有一个日期列,它是添加行的日期时间。

This is one I use to get the last 10 rows:这是我用来获取最后 10 行的:

SELECT id FROM mytable order by date desc LIMIT 10

I know I can do SELECT id FROM mytable ORDER BY RAND() LIMIT 1 but that just choose any random row, not from the last 10 rows.我知道我可以做SELECT id FROM mytable ORDER BY RAND() LIMIT 1 ,但只选择任何随机行,而不是从最后 10 行。

One method uses a subquery:一种方法使用子查询:

SELECT t.*
FROM (SELECT id
      FROM mytable 
      ORDER BY date DESC
      LIMIT 10
     ) t
ORDER BY rand()
LIMIT 1;

This version uses the syntax conventions for MySQL.此版本使用 MySQL 的语法约定。

You can use select * in the subquery to fetch the whole row.您可以在子查询中使用select *来获取整行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM