我们可以在 MySQL 中按一列进行 GROUP BY 并选择所有数据吗?
是的,你可以对此使用 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)
广告