在单个 MySQL 查询中按两列的函数排序
mysqlmysqli database
让我们首先创建一个表
mysql> create table orderByAFunctionDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> FirstNumber int, -> SecodNumber int -> ); Query OK, 0 rows affected (0.44 sec)
使用 insert 命令在表中插入一些记录。 查询语句如下 −
mysql> insert into orderByAFunctionDemo(FirstNumber,SecodNumber) values(10,4); Query OK, 1 row affected (0.11 sec) mysql> insert into orderByAFunctionDemo(FirstNumber,SecodNumber) values(45,78); Query OK, 1 row affected (0.17 sec) mysql> insert into orderByAFunctionDemo(FirstNumber,SecodNumber) values(23,10); Query OK, 1 row affected (0.12 sec) mysql> insert into orderByAFunctionDemo(FirstNumber,SecodNumber) values(67,237); Query OK, 1 row affected (0.16 sec) mysql> insert into orderByAFunctionDemo(FirstNumber,SecodNumber) values(12,90); Query OK, 1 row affected (0.13 sec)
使用 select 语句显示表中的所有记录。查询如下 −
mysql> select *from orderByAFunctionDemo;
以下是输出 −
+----+-------------+-------------+ | Id | FirstNumber | SecondNumber| +----+-------------+-------------+ | 1 | 10 | 4 | | 2 | 45 | 78 | | 3 | 23 | 10 | | 4 | 67 | 237 | | 5 | 12 | 90 | +----+-------------+-------------+ 5 rows in set (0.00 sec)
以下是按两列函数排序的查询。查询如下 −
mysql> select (4*FirstNumber+5*SecondNumber) as Calculation -> from orderByAFunctionDemo -> order by Calculation desc;
以下是输出 −
+-------------+ | Calculation | +-------------+ | 1453 | | 570 | | 498 | | 142 | | 60 | +-------------+ 5 rows in set (0.00 sec)