如何在单个 MySQL 字段中使用 ORDER BY 字段并按 id 排序?
为此,可以使用 ORDER BY FIELD。我们首先创建一个表 -
mysql> create table DemoTable -> ( -> Id int, -> Name varchar(20) -> ); Query OK, 0 rows affected (1.78 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable values(101,'Chris'); Query OK, 1 row affected (0.38 sec) mysql> insert into DemoTable values(201,'Mike'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(110,'Adam'); Query OK, 1 row affected (0.52 sec) mysql> insert into DemoTable values(250,'John'); Query OK, 1 row affected (0.33 sec)
使用 select 语句从表中显示所有记录 -
mysql> select *from DemoTable;
这将产生以下输出 -
+------+-------+ | Id | Name | +------+-------+ | 101 | Chris | | 201 | Mike | | 110 | Adam | | 250 | John | +------+-------+ 4 rows in set (0.00 sec)
以下是对照字段进行排序以及按 id 进行排序的查询;
mysql> select *from DemoTable -> order by field(Name,'Mike') desc,Id desc;
这将产生以下输出 -
+------+-------+ | Id | Name | +------+-------+ | 201 | Mike | | 250 | John | | 110 | Adam | | 101 | Chris | +------+-------+ 4 rows in set (0.01 sec)
广告