我们可以在 MySQL 中按一列分组并选择所有数据吗?
mysqlmysqli database
是的,您可以使用 group_concat() 来实现这一点。让我们首先创建一个表 −
mysql> create table groupByOneSelectAll -> ( -> StudentDetails varchar(100), -> StudentName varchar(100) -> ); Query OK, 0 rows affected (0.91 sec)
下面是使用 insert 命令在表中插入一些记录的查询 −
mysql> insert into groupByOneSelectAll values('StudentFirstName','John'); Query OK, 1 row affected (0.14 sec) mysql> insert into groupByOneSelectAll values('StudentFirstName','Chris'); Query OK, 1 row affected (0.21 sec) mysql> insert into groupByOneSelectAll values('StudentFirstName','Robert'); Query OK, 1 row affected (0.65 sec) mysql> insert into groupByOneSelectAll values('StudentFirstName','Bob'); Query OK, 1 row affected (0.13 sec) mysql> insert into groupByOneSelectAll values('StudentFirstName','David'); Query OK, 1 row affected (0.15 sec)
以下是使用 select 语句显示表中的所有记录的查询 −
mysql> select * from groupByOneSelectAll;
这将产生以下输出 −
+------------------+-------------+ | StudentDetails | StudentName | +------------------+-------------+ | StudentFirstName | John | | StudentFirstName | Chris | | StudentFirstName | Robert | | StudentFirstName | Bob | | StudentFirstName | David | +------------------+-------------+ 5 rows in set (0.00 sec)
以下是按单列分组的查询 −
mysql> select StudentDetails,group_concat(StudentName) from groupByOneSelectAll group by StudentDetails;
这将产生以下输出 −
+------------------+-----------------------------+ | StudentDetails | group_concat(StudentName) | +------------------+-----------------------------+ | StudentFirstName | John,Chris,Robert,Bob,David | +------------------+-----------------------------+ 1 row in set (0.05 sec)