Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

สลับลำดับข้อมูลในตาราง MySQL ด้วย RAND()

ใช้ ORDER BY RAND() เพื่อสุ่มลำดับแถวทุกครั้งที่รันคิวรี

สร้างตารางและเพิ่มข้อมูล

mysql> create table DemoTable792 ( Name varchar(100), Subject varchar(100) ); 
Query OK, 0 rows affected (0.66 sec)

mysql> insert into DemoTable792 values('Chris','MySQL'); Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable792 values('David','MySQL'); Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable792 values('Robert','MongoDB'); Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable792 values('Carol','MongoDB'); Query OK, 1 row affected (0.18 sec)

คิวรีสุ่มลำดับ

mysql> select * from DemoTable792 order by rand();
+--------+---------+
| Name   | Subject |
+--------+---------+
| Chris  | MySQL   |
| Robert | MongoDB |
| David  | MySQL   |
| Carol  | MongoDB |
+--------+---------+
4 rows in set (0.00 sec)

ข้อควรระวัง: ORDER BY RAND() ช้าในตารางใหญ่ เพราะต้องสุ่มทุกแถว สำหรับตารางใหญ่ควรสุ่มในระดับแอปพลิเคชันแทน