如何从MySQL的20个最新行中选择5个随机行?
对于随机,请使用RAND()方法。对于行的限制,请使用LIMIT()方法。
让我们首先创建一个表-
create table DemoTable -> ( -> ShippingDate datetime -> );
使用插入命令在表中插入一些记录-
insert into DemoTable values('2019-01-01'); insert into DemoTable values('2019-01-03'); insert into DemoTable values('2019-01-05'); insert into DemoTable values('2019-01-07'); insert into DemoTable values('2019-02-02'); insert into DemoTable values('2019-02-04'); insert into DemoTable values('2019-02-12'); insert into DemoTable values('2019-02-24'); insert into DemoTable values('2019-02-25'); insert into DemoTable values('2019-03-10'); insert into DemoTable values('2019-03-11'); insert into DemoTable values('2019-03-12'); insert into DemoTable values('2019-03-14'); insert into DemoTable values('2019-03-16'); insert into DemoTable values('2019-03-18'); insert into DemoTable values('2019-03-20'); insert into DemoTable values('2019-03-25'); insert into DemoTable values('2019-03-28'); insert into DemoTable values('2019-03-29'); insert into DemoTable values('2019-04-03'); insert into DemoTable values('2019-04-03'); insert into DemoTable values('2019-04-04'); insert into DemoTable values('2019-04-06'); insert into DemoTable values('2019-04-09'); insert into DemoTable values('2019-05-01'); insert into DemoTable values('2019-05-13'); insert into DemoTable values('2019-05-15'); insert into DemoTable values('2019-05-16'); insert into DemoTable values('2019-05-18');
使用select语句显示表中的所有记录-
select *from DemoTable;
输出结果
这将产生以下输出-
+---------------------+ | ShippingDate | +---------------------+ | 2019-01-01 00:00:00 | | 2019-01-03 00:00:00 | | 2019-01-05 00:00:00 | | 2019-01-07 00:00:00 | | 2019-02-02 00:00:00 | | 2019-02-04 00:00:00 | | 2019-02-12 00:00:00 | | 2019-02-24 00:00:00 | | 2019-02-25 00:00:00 | | 2019-03-10 00:00:00 | | 2019-03-11 00:00:00 | | 2019-03-12 00:00:00 | | 2019-03-14 00:00:00 | | 2019-03-16 00:00:00 | | 2019-03-18 00:00:00 | | 2019-03-20 00:00:00 | | 2019-03-25 00:00:00 | | 2019-03-28 00:00:00 | | 2019-03-29 00:00:00 | | 2019-04-03 00:00:00 | | 2019-04-03 00:00:00 | | 2019-04-04 00:00:00 | | 2019-04-06 00:00:00 | | 2019-04-09 00:00:00 | | 2019-05-01 00:00:00 | | 2019-05-13 00:00:00 | | 2019-05-15 00:00:00 | | 2019-05-16 00:00:00 | | 2019-05-18 00:00:00 | +---------------------+ 29 rows in set (0.00 sec)
以下是从20个最新行中选择5个随机行的查询-
select tbl1.* from (select *from DemoTable ORDER BY ShippingDate DESC LIMIT 20 ) as tbl1 -> ORDER BY RAND() LIMIT 5;
输出结果
这将产生以下输出-
+---------------------+ | ShippingDate | +---------------------+ | 2019-03-14 00:00:00 | | 2019-05-13 00:00:00 | | 2019-03-25 00:00:00 | | 2019-05-16 00:00:00 | | 2019-03-10 00:00:00 | +---------------------+ 5 rows in set (0.04 sec)