MySQL 中使用随机值列随机排序?
我们首先创建一个表格。之后,我们将创建一个新的随机值列并对记录进行随机排序
mysql> create table DemoTable ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentName varchar(20) ); Query OK, 0 rows affected (0.57 sec)
以下是使用 insert 命令在表中插入一些记录的查询
mysql> insert into DemoTable(StudentName) values('Larry'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable(StudentName) values('Sam'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable(StudentName) values('Mike'); Query OK, 1 row affected (0.34 sec) mysql> insert into DemoTable(StudentName) values('Carol'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(StudentName) values('Robert'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable(StudentName) values('Chris'); Query OK, 1 row affected (0.14 sec)
以下是使用 select 语句从表中显示记录的查询
mysql> select *from DemoTable;
这将产生以下输出
+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 1 | Larry | | 2 | Sam | | 3 | Mike | | 4 | Carol | | 5 | Robert | | 6 | Chris | +-----------+-------------+ 6 rows in set (0.00 sec)
以下是按随机字段排序的查询。我们在这里创建了一个新的随机字段
mysql> SELECT * FROM (SELECT StudentName, RAND()+1 AS randomRecord FROM DemoTable ) tbl ORDER BY RandomRecord DESC;
这将产生以下输出
+-------------+--------------------+ | StudentName | RandomRecord | +-------------+--------------------+ | Carol | 1.8973721451101566 | | Chris | 1.7821308670399065 | | Mike | 1.4640037673190271 | | Larry | 1.4134691557041081 | | Sam | 1.1408822407395414 | | Robert | 1.0948494543273461 | +-------------+--------------------+ 6 rows in set (0.00 sec)
广告