如何以指定顺序排列 MySQL 数据?
使用 `ORDER BY IF()` 以特定顺序排列数据。语法如下 −
select *from yourTableName ORDER BY IF(yourColumnName=yourValue1 OR yourColumnName=yourValue2 OR yourColumnName=yourValue3,yourColumnName, ~yourColumnName) ASC;
我们首先创建一个表 −
mysql> create table arrangeDataInSpecificOrder -> ( -> StudentId int, -> StudentName varchar(20) -> ); Query OK, 0 rows affected (0.64 sec)
以下是使用 `insert` 命令向表中插入一些记录的查询 −
mysql> insert into arrangeDataInSpecificOrder values(10,'Larry'); Query OK, 1 row affected (0.12 sec) mysql> insert into arrangeDataInSpecificOrder values(15,'Mike'); Query OK, 1 row affected (0.09 sec) mysql> insert into arrangeDataInSpecificOrder values(100,'Sam'); Query OK, 1 row affected (0.16 sec) mysql> insert into arrangeDataInSpecificOrder values(70,'Carol'); Query OK, 1 row affected (0.12 sec) mysql> insert into arrangeDataInSpecificOrder values(90,'Bob'); Query OK, 1 row affected (0.14 sec) mysql> insert into arrangeDataInSpecificOrder values(300,'David'); Query OK, 1 row affected (0.12 sec)
以下是使用 `select` 语句从表中显示所有记录的查询 −
mysql> select * from arrangeDataInSpecificOrder;
这将产生以下输出 −
+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 10 | Larry | | 15 | Mike | | 100 | Sam | | 70 | Carol | | 90 | Bob | | 300 | David | +-----------+-------------+ 6 rows in set (0.00 sec)
以下是按特定顺序排列数据的查询 −
mysql> select * from arrangeDataInSpecificOrder ORDER BY IF(StudentId=300 OR StudentId=100 OR StudentId=10,StudentId, ~StudentId) ASC;
这将产生以下输出 −
+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 10 | Larry | | 100 | Sam | | 300 | David | | 90 | Bob | | 70 | Carol | | 15 | Mike | +-----------+-------------+ 6 rows in set (0.00 sec)
广告