用 MySQL 随机排列列值?
若要随机排列元素,需要使用 ORDER BY RAND()。我们首先创建一个表 −
mysql> create table DemoTable1557 -> ( -> SubjectId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> SubjectName varchar(20) -> ); Query OK, 0 rows affected (0.91 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable1557(SubjectName) values('MySQL'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1557(SubjectName) values('MongoDB'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1557(SubjectName) values('Java'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1557(SubjectName) values('C'); Query OK, 1 row affected (0.13 sec)
使用 select 从表中显示所有记录 −
mysql> select * from DemoTable1557;
这将产生以下输出 −
+-----------+-------------+ | SubjectId | SubjectName | +-----------+-------------+ | 1 | MySQL | | 2 | MongoDB | | 3 | Java | | 4 | C | +-----------+-------------+ 4 rows in set (0.00 sec)
以下是使用 MySQL 随机排列记录的查询 −
mysql> select * from DemoTable1557 order by rand();
这将产生以下输出 −
+-----------+-------------+ | SubjectId | SubjectName | +-----------+-------------+ | 1 | MySQL | | 3 | Java | | 2 | MongoDB | | 4 | C | +-----------+-------------+ 4 rows in set (0.00 sec)
广告