简体   繁体   中英

how to select a list from random id to the last

im new with SQL. i know to how select a list with limit comand. but that way need a value to select. what if i want select a list from random id to the last. exemple:

I want to select a list with id from 4 -> last of row (cuz i dont know whats last id)

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

where thing1 is your table name. How you seed your random number generator (RNG) is up to you.

+----+---------+------------+
| 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)

Stored Proc

To have starting random position, until the end, random ordering

-- 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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