将 MySQL 行按列值分组到一个数组中?
若要将行分组到一个数组中,请将 GROUP_CONCAT() 与 ORDER BY 子句一起使用。让我们首先创建一个表 -
mysql> create table DemoTable -> ( -> Id int, -> FirstName varchar(20) -> ); Query OK, 0 rows affected (0.78 sec)
使用 insert 命令向表中插入一些记录 -
mysql> insert into DemoTable values(101,'John'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(102,'Bob'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable values(101,'David'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(101,'Adam'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(102,'Chris'); Query OK, 1 row affected (0.15 sec)
使用 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)
广告