MySQL 中按特定的列名对随机行进行排序?
首先,让我们创建一个表 −
mysql> create table DemoTable1339 -> ( -> Name varchar(30), -> Score int -> ); Query OK, 0 rows affected (0.76 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable1339 values('Chris',56); Query OK, 1 row affected (0.36 sec) mysql> insert into DemoTable1339 values('Bob',46); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable1339 values('Adam',78); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable1339 values('John',90); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable1339 values('Carol',98); Query OK, 1 row affected (0.12 sec)
使用 select 语句显示表中的所有记录 −
mysql> select * from DemoTable1339;
这将生成以下输出 −
+-------+-------+ | Name | Score | +-------+-------+ | Chris | 56 | | Bob | 46 | | Adam | 78 | | John | 90 | | Carol | 98 | +-------+-------+ 5 rows in set (0.00 sec)
以下是对 NAME 列进行随机行排序的查询 −
mysql> select * from (select *from DemoTable1339 order by rand() limit 4) tbl order by Name;
这将生成以下输出 −
+-------+-------+ | Name | Score | +-------+-------+ | Adam | 78 | | Bob | 46 | | Carol | 98 | | Chris | 56 | +-------+-------+ 4 rows in set (0.05 sec)
广告