让我们首先创建一个表。之后,我们将创建一个新的随机值列,并对记录进行随机排序:
mysql> create table DemoTable ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentName varchar(20) );
以下是使用insert命令在表中插入一些记录的查询:
mysql> insert into DemoTable(StudentName) values('Larry'); mysql> insert into DemoTable(StudentName) values('Sam'); mysql> insert into DemoTable(StudentName) values('Mike'); mysql> insert into DemoTable(StudentName) values('Carol'); mysql> insert into DemoTable(StudentName) values('Robert'); mysql> insert into DemoTable(StudentName) values('Chris');
以下是使用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)