如果初始行是随机的并且其余行是通过 MySQL 中的条件排序的,如何选择行?
为此,可以使用 ORDER BY CASE 语句。让我们创建一个表 -
mysql> create table DemoTable1926 ( Position varchar(20), Number int ); Query OK, 0 rows affected (0.00 sec)
使用 insert 命令向表中插入一些记录 -
mysql> insert into DemoTable1926 values('Highest',50); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1926 values('Highest',30); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1926 values('Lowest',100); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1926 values('Lowest',120); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1926 values('Lowest',90); Query OK, 1 row affected (0.00 sec)
使用 select 语句显示表中的所有记录 -
mysql> select * from DemoTable1926;
这将产生以下结果 -
+----------+--------+ | Position | Number | +----------+--------+ | Highest | 50 | | Highest | 30 | | Lowest | 100 | | Lowest | 120 | | Lowest | 90 | +----------+--------+ 5 rows in set (0.00 sec)
以下是选择行的查询,如果初始行是随机的,并且其余行是按条件排序的 -
mysql> select * from DemoTable1926 order by Position desc,case Position when 'Highest' then rand() else Number end asc;
这将产生以下结果 -
+----------+--------+ | Position | Number | +----------+--------+ | Lowest | 90 | | Lowest | 100 | | Lowest | 120 | | Highest | 50 | | Highest | 30 | +----------+--------+ 5 rows in set (0.00 sec)
广告