Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

ORDER BY RAND() và giữ nhóm trong MySQL

Tạo bảng với dữ liệu trùng lặp:

mysql> create table DemoTable
    -> (
    -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
    -> StudentMarks int
    -> );
Query OK, 0 rows affected (0.58 sec)
mysql> insert into DemoTable(StudentMarks) values(98);
mysql> insert into DemoTable(StudentMarks) values(98);
mysql> insert into DemoTable(StudentMarks) values(78);
mysql> insert into DemoTable(StudentMarks) values(78);
mysql> insert into DemoTable(StudentMarks) values(45);
mysql> insert into DemoTable(StudentMarks) values(56);

Dữ liệu ban đầu:

+-----------+--------------+
| StudentId | StudentMarks |
+-----------+--------------+
| 1         | 98           |
| 2         | 98           |
| 3         | 78           |
| 4         | 78           |
| 5         | 45           |
| 6         | 56           |
+-----------+--------------+

Truy vấn ngẫu nhiên nhưng giữ nhóm:

mysql> select * from DemoTable order by rand(StudentMarks*100*RAND());
+-----------+--------------+
| StudentId | StudentMarks |
+-----------+--------------+
| 3         | 78           |
| 6         | 56           |
| 5         | 45           |
| 4         | 78           |
| 1         | 98           |
| 2         | 98           |
+-----------+--------------+

Giải thích: Biểu thức rand(StudentMarks*100*RAND()) tạo giá trị ngẫu nhiên nhưng các bản ghi cùng StudentMarks sẽ có giá trị ngẫu nhiên tương đối gần nhau, giúp giữ nhóm.