对 MySQL 记录进行随机排序并按升序显示名称
mysqlmysqli database
您可以使用子查询随机排序并按升序显示名称。rand() 用于随机排序,而 ORDER BY 用于按升序显示名称记录。语法如下 −
select *from ( select *from yourTableName order by rand() limit anyIntegerValue; ) anyVariableName order by yourColumnName;
为了理解上述概念,让我们创建一个表。我们有一个 ID 为 sell 的 Name,我们希望按升序排列。创建表的查询如下 −
mysql> create table OrderByRandName −> ( −> Id int, −> Name varchar(100) −> ); Query OK, 0 rows affected (0.96 sec)
使用 insert 命令显示表中的所有记录。查询如下 −
mysql> insert into OrderByRandName values(100,'John'); Query OK, 1 row affected (0.18 sec) mysql> insert into OrderByRandName values(101,'Bob'); Query OK, 1 row affected (0.11 sec) mysql> insert into OrderByRandName values(102,'Johnson'); Query OK, 1 row affected (0.19 sec) mysql> insert into OrderByRandName values(103,'David'); Query OK, 1 row affected (0.22 sec) mysql> insert into OrderByRandName values(104,'Smith'); Query OK, 1 row affected (0.17 sec) mysql> insert into OrderByRandName values(105,'Taylor'); Query OK, 1 row affected (0.20 sec) mysql> insert into OrderByRandName values(106,'Sam'); Query OK, 1 row affected (0.12 sec) mysql> insert into OrderByRandName values(107,'Robert'); Query OK, 1 row affected (0.22 sec) mysql> insert into OrderByRandName values(108,'Michael'); Query OK, 1 row affected (0.16 sec) mysql> insert into OrderByRandName values(109,'Mark'); Query OK, 1 row affected (0.17 sec)
使用 select 语句显示所有记录。 查询语句如下 −
mysql> select *from OrderByRandName;
以下是输出 −
+------+---------+ | Id | Name | +------+---------+ | 100 | John | | 101 | Bob | | 102 | Johnson | | 103 | David | | 104 | Smith | | 105 | Taylor | | 106 | Sam | | 107 | Robert | | 108 | Michael | | 109 | Mark | +------+---------+ 10 rows in set (0.00 sec)
这是按 rand() 排序并按升序显示名称的查询 −
mysql> select *from −> ( −> select *from OrderByRandName order by rand() limit 10 −> )tbl1 −> order by Name;
以下是输出 −
+------+---------+ | Id | Name | +------+---------+ | 101 | Bob | | 103 | David | | 100 | John | | 102 | Johnson | | 109 | Mark | | 108 | Michael | | 107 | Robert | | 106 | Sam | | 104 | Smith | | 105 | Taylor | +------+---------+ 10 rows in set (0.39 sec)