이를 위해서는 ORDER BY를 사용하여 레코드를 주문해야 합니다. RAND()를 사용하여 임의의 레코드를 가져오고 5개의 임의 레코드만 표시하기를 원하므로 LIMIT 5를 사용합니다.
먼저 테이블을 생성하겠습니다 -
mysql> create table DemoTable773 (StudentId int); Query OK, 0 rows affected (0.59 sec)
삽입 명령을 사용하여 테이블에 일부 레코드 삽입 -
mysql> insert into DemoTable773 values(100); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable773 values(200); Query OK, 1 row affected (0.87 sec) mysql> insert into DemoTable773 values(300); Query OK, 1 row affected (1.59 sec) mysql> insert into DemoTable773 values(400); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable773 values(500); Query OK, 1 row affected (0.29 sec) mysql> insert into DemoTable773 values(1); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable773 values(2); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable773 values(3); Query OK, 1 row affected (0.07 sec) mysql> insert into DemoTable773 values(4); Query OK, 1 row affected (0.73 sec) mysql> insert into DemoTable773 values(5); Query OK, 1 row affected (0.77 sec) mysql> insert into DemoTable773 values(6); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable773 values(7); Query OK, 1 row affected (0.24 sec) mysql> insert into DemoTable773 values(8); Query OK, 1 row affected (0.50 sec) mysql> insert into DemoTable773 values(9); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable773 values(10); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable773 values(90); Query OK, 1 row affected (0.26 sec) mysql> insert into DemoTable773 values(91); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable773 values(92); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable773 values(93); Query OK, 1 row affected (0.33 sec) mysql> insert into DemoTable773 values(94); Query OK, 1 row affected (0.38 sec) mysql> insert into DemoTable773 values(95); Query OK, 1 row affected (0.34 sec) mysql> insert into DemoTable773 values(96); Query OK, 1 row affected (0.24 sec) mysql> insert into DemoTable773 values(97); Query OK, 1 row affected (0.27 sec)
select 문을 사용하여 테이블의 모든 레코드 표시 -
mysql> select *from DemoTable773;
그러면 다음과 같은 출력이 생성됩니다. -
+-----------+ | StudentId | +-----------+ | 100 | | 200 | | 300 | | 400 | | 500 | | 1 | | 2 | | 3 | | 4 | | 5 | | 6 | | 7 | | 8 | | 9 | | 10 | | 90 | | 91 | | 92 | | 93 | | 94 | | 95 | | 96 | | 97 | +-----------+ 23 rows in set (0.00 sec)
다음은
에서 5개의 임의 레코드를 반환하는 쿼리입니다.최근 20개 레코드 -
mysql> select *from ( select * from DemoTable773 order by StudentId desc limit 20 ) AS RANDOM_OUTPUT order by rand() limit 5;
그러면 다음과 같은 출력이 생성됩니다. -
+-----------+ | StudentId | +-----------+ | 95 | | 4 | | 10 | | 7 | | 300 | +-----------+ 5 rows in set (0.51 sec)