在 MySQL 中使用 ORDER BY rand() 并在其中保持分组?
我们先创建一个表格 −
mysql> create table DemoTable -> ( -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> StudentMarks int -> ); Query OK, 0 rows affected (0.58 sec)
使用 insert 命令在表格中插入一些记录。我们还插入了重复的记录 −
mysql> insert into DemoTable(StudentMarks) values(98); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable(StudentMarks) values(98); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable(StudentMarks) values(78); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable(StudentMarks) values(78); Query OK, 1 row affected (0.29 sec) mysql> insert into DemoTable(StudentMarks) values(45); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable(StudentMarks) values(56); Query OK, 1 row affected (0.09 sec)
使用 select 语句显示表格中的所有记录 −
mysql> select *from DemoTable;
这将产生以下输出 −
+-----------+--------------+ | StudentId | StudentMarks | +-----------+--------------+ | 1 | 98 | | 2 | 98 | | 3 | 78 | | 4 | 78 | | 5 | 45 | | 6 | 56 | +-----------+--------------+ 6 rows in set (0.00 sec)
以下是按 rand() 进行排序并保持分组的查询 −
mysql> select *from DemoTable order by rand(StudentMarks*100*RAND());
这将产生以下输出。此处,98 分记录保持分组 −
+-----------+--------------+ | StudentId | StudentMarks | +-----------+--------------+ | 3 | 78 | | 6 | 56 | | 5 | 45 | | 4 | 78 | | 1 | 98 | | 2 | 98 | +-----------+--------------+ 6 rows in set (0.00 sec)
广告