您可以使用ORDER BYIF()
来获取特定顺序的记录。让我们首先创建一个表:
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstName varchar(20), Branch varchar(20) );
以下是使用insert命令在表中插入一些记录的查询:
mysql> insert into DemoTable(FirstName,Branch) values('John','CS'); mysql> insert into DemoTable(FirstName,Branch) values('Carol','ME'); mysql> insert into DemoTable(FirstName,Branch) values('David','ME'); mysql> insert into DemoTable(FirstName,Branch) values('Bob','CE'); mysql> insert into DemoTable(FirstName,Branch) values('Robert','EE'); mysql> insert into DemoTable(FirstName,Branch) values('Chris','EEE'); mysql> insert into DemoTable(FirstName,Branch) values('James','ME');
以下是使用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)