MySQL 查询如何根据相应列中的 1 个值对 concat 进行分组并将数据放入一行?
mysqlmysqli database更新于 2024/4/4 8:57:00
为此,请使用 GROUP_CONCAT()。对于只有 1 个值的情况,请使用 MySQL WHERE 子句。让我们首先创建一个表 −
mysql> create table DemoTable ( PlayerName varchar(40), PlayerStatus tinyint(1) ); Query OK, 0 rows affected (0.60 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values('Chris',1); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('David',0); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('Sam',1); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('Carol',1); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('Bob',0); Query OK, 1 row affected (0.14 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
这将产生以下输出 −
+------------+--------------+ | PlayerName | PlayerStatus | +------------+--------------+ | Chris | 1 | | David | 0 | | Sam | 1 | | Carol | 1 | | Bob | 0 | +------------+--------------+ 5 rows in set (0.00 sec)
以下查询用于根据相应列中的 1 个值对连接数据进行分组并将数据放入一行中 −
mysql> select group_concat(PlayerName) from DemoTable where PlayerStatus=1;
这将产生以下输出 −
+--------------------------+ | group_concat(PlayerName) | +--------------------------+ | Chris,Sam,Carol | +--------------------------+ 1 row in set (0.00 sec)