通过列值将数组中的MySQL行分组?
要将数组中的行分组,请使用GROUP_CONCAT()以及ORDER BY子句。让我们首先创建一个表-
mysql> create table DemoTable-> (
-> Id int,
-> FirstName varchar(20)
-> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values(101,'John');mysql> insert into DemoTable values(102,'Bob');
mysql> insert into DemoTable values(101,'David');
mysql> insert into DemoTable values(101,'Adam');
mysql> insert into DemoTable values(102,'Chris');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+------+-----------+| Id | FirstName |
+------+-----------+
| 101 | John |
| 102 | Bob |
| 101 | David |
| 101 | Adam |
| 102 | Chris |
+------+-----------+
5 rows in set (0.00 sec)
这是按列值将数组中的MySQL行分组的查询-
mysql> select Id,group_concat(FirstName separator ',') from DemoTable-> group by Id
-> order by count(Id);
这将产生以下输出-
+------+---------------------------------------+| Id | group_concat(FirstName separator ',') |
+------+---------------------------------------+
| 102 | Bob,Chris |
| 101 | John,David,Adam |
+------+---------------------------------------+
2 rows in set (0.00 sec)
以上是 通过列值将数组中的MySQL行分组? 的全部内容, 来源链接: utcz.com/z/326562.html