使用 MySQL 获取特定顺序的记录?
可以使用 ORDER BY IF() 来获取特定顺序的记录。让我们先创建一个表
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstName varchar(20), Branch varchar(20) ); Query OK, 0 rows affected (1.96 sec)
以下是用 insert 命令将某些记录插入表的查询
mysql> insert into DemoTable(FirstName,Branch) values('John','CS'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable(FirstName,Branch) values('Carol','ME'); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable(FirstName,Branch) values('David','ME'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable(FirstName,Branch) values('Bob','CE'); Query OK, 1 row affected (0.35 sec) mysql> insert into DemoTable(FirstName,Branch) values('Robert','EE'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable(FirstName,Branch) values('Chris','EEE'); Query OK, 1 row affected (0.27 sec) mysql> insert into DemoTable(FirstName,Branch) values('James','ME'); Query OK, 1 row affected (0.56 sec)
以下是用 select 命令从表中显示记录的查询
mysql> select *from DemoTable;
这会产生以下输出
+----+-----------+--------+ | Id | FirstName | Branch | +----+-----------+--------+ | 1 | John | CS | | 2 | Carol | ME | | 3 | David | ME | | 4 | Bob | CE | | 5 | Robert | EE | | 6 | Chris | EEE | | 7 | James | ME | +----+-----------+--------+ 7 rows in set (0.00 sec)
以下是使用 MySQL 获取特定顺序的记录的查询。我们设置的顺序从‘ME’分支开始
mysql> select *from DemoTable order by if(Branch='ME',1,0)DESC,Branch;
这会产生以下输出
+----+-----------+--------+ | Id | FirstName | Branch | +----+-----------+--------+ | 2 | Carol | ME | | 3 | David | ME | | 7 | James | ME | | 4 | Bob | CE | | 1 | John | CS | | 5 | Robert | EE | | 6 | Chris | EEE | +----+-----------+--------+ 7 rows in set (0.00 sec)
广告