如何在 MySQL GROUP BY 子句中排序或选择行?
mysqlmysqli database更新于 2024/8/9 15:40:17
首先我们创建一个表 −
mysql> create table DemoTable1572 -> ( -> StudentId int, -> StudentMarks int, -> StudentName varchar(20) -> ); Query OK, 0 rows affected (0.56 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable1572 values(1,79,'Sam'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable1572 values(2,89,'Chris'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable1572 values(3,98,'David'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable1572 values(4,79,'Bob'); Query OK, 1 row affected (0.10 sec)
使用 select 语句显示表中的所有记录 −
mysql> select * from DemoTable1572;
这将产生以下输出 −
+-----------+--------------+-------------+ | StudentId | StudentMarks | StudentName | +-----------+--------------+-------------+ | 1 | 79 | Sam | | 2 | 89 | Chris | | 3 | 98 | David | | 4 | 79 | Bob | +-----------+--------------+-------------+ 4 rows in set (0.00 sec)
这是在 MySQL GROUP BY 子句中对行进行排序或选择的查询 −
mysql> select * from DemoTable1572 -> where StudentId in (select min(StudentId) from DemoTable1572 group by StudentMarks);
这将产生以下输出 −
+-----------+--------------+-------------+ | StudentId | StudentMarks | StudentName | +-----------+--------------+-------------+ | 1 | 79 | Sam | | 2 | 89 | Chris | | 3 | 98 | David | +-----------+--------------+-------------+ 3 rows in set (0.10 sec)
相关文章
有用资源
mysql 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/

