按 id 选择不同顺序的 MySQL 查询
为此,使用 ORDER BY MAX()。我们先创建一个表 −
mysql> create table DemoTable -> ( -> Id int, -> Name varchar(100) -> ); Query OK, 0 rows affected (0.81 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values(10,'John'); Query OK, 1 row affected (0.51 sec) mysql> insert into DemoTable values(10,'John'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(20,'Sam'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values(20,'Sam'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values(30,'David'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(30,'David'); Query OK, 1 row affected (0.11 sec)
使用 select 语句在表中显示所有记录 −
mysql> select *from DemoTable;
输出
这将产生以下输出 −
+------+-------+ | Id | Name | +------+-------+ | 10 | John | | 10 | John | | 20 | Sam | | 20 | Sam | | 30 | David | | 30 | David | +------+-------+ 6 rows in set (0.00 sec)
以下是按 id 选择不同顺序的查询 −
mysql> select Name from DemoTable -> group by Name -> order by max(Id) DESC -> limit 2;
输出
这将产生以下输出 −
+-------+ | Name | +-------+ | David | | Sam | +-------+ 2 rows in set (0.06 sec)
广告