如何从随机id到最后一个选择列表

时间:2015-08-24 14:17:32

标签: mysql sql

我是SQL的新手。我知道如何选择具有限制命令的列表。但这种方式需要一个值来选择。如果我想要从随机id到最后一个选择一个列表。例如:

我想选择ID为4的列表 - >行的最后一个(因为我不知道最后一个id)

1 个答案:

答案 0 :(得分:1)

select * from thing1 where id>=4 order by rand();

其中thing1是您的表名。种子随机数生成器(RNG)的种子由您决定。

+----+---------+------------+
| id | conn_id | read_date  |
+----+---------+------------+
| 11 |       3 | 2013-02-21 |
|  5 |       1 | 2012-02-21 |
|  8 |       5 | 2010-12-21 |
| 15 |       7 | 2019-12-21 |
| 14 |       6 | 2019-12-21 |
| 13 |       5 | 2016-02-21 |
|  4 |       2 | 2010-12-21 |
|  7 |       2 | 2014-02-21 |
|  6 |       2 | 2007-12-21 |
| 12 |       4 | 2014-02-21 |
| 16 |       8 | 2010-12-21 |
|  9 |       3 | 2010-12-21 |
| 10 |       4 | 2010-12-21 |
+----+---------+------------+
13 rows in set (0.14 sec)

mysql> select * from thing1 where id>=4 order by rand();
+----+---------+------------+
| id | conn_id | read_date  |
+----+---------+------------+
| 13 |       5 | 2016-02-21 |
|  6 |       2 | 2007-12-21 |
| 10 |       4 | 2010-12-21 |
| 16 |       8 | 2010-12-21 |
| 14 |       6 | 2019-12-21 |
|  5 |       1 | 2012-02-21 |
|  7 |       2 | 2014-02-21 |
| 11 |       3 | 2013-02-21 |
| 12 |       4 | 2014-02-21 |
|  4 |       2 | 2010-12-21 |
|  8 |       5 | 2010-12-21 |
|  9 |       3 | 2010-12-21 |
| 15 |       7 | 2019-12-21 |
+----+---------+------------+
13 rows in set (0.02 sec)

mysql> select * from thing1 where id>=4 order by rand();
+----+---------+------------+
| id | conn_id | read_date  |
+----+---------+------------+
| 10 |       4 | 2010-12-21 |
|  4 |       2 | 2010-12-21 |
|  6 |       2 | 2007-12-21 |
|  7 |       2 | 2014-02-21 |
|  5 |       1 | 2012-02-21 |
|  9 |       3 | 2010-12-21 |
| 12 |       4 | 2014-02-21 |
| 16 |       8 | 2010-12-21 |
|  8 |       5 | 2010-12-21 |
| 15 |       7 | 2019-12-21 |
| 13 |       5 | 2016-02-21 |
| 14 |       6 | 2019-12-21 |
| 11 |       3 | 2013-02-21 |
+----+---------+------------+
13 rows in set (0.05 sec)

存储过程

要有起始随机位置,直到结束,随机排序

-- drop procedure getRandomStartToEnd;
delimiter $$
create procedure getRandomStartToEnd()
BEGIN
    declare theCount int;
    declare theStart int;

    select count(*) into theCount from thing1;
    set @theStart:=floor((rand()*@theCount)+1);
    select * from thing1 where id>=@theStart order by rand();
END
$$

call getRandomStartToEnd;   -- call stored proc