Pesquisa de site

Consulta MySQL para agrupar concat e colocar dados em uma única linha com base em 1 valor na coluna correspondente?


Para isso utilize GROUP_CONCAT(). Para apenas 1 valor, trabalhe com a cláusula WHERE do MySQL. Vamos primeiro criar uma tabela:

mysql> create table DemoTable
(
   PlayerName varchar(40),
   PlayerStatus tinyint(1)
);
Query OK, 0 rows affected (0.60 sec)

Insira alguns registros na tabela usando o comando 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)

Exiba todos os registros da tabela usando a instrução select:

mysql> select *from DemoTable;

Isso produzirá a seguinte saída:

+------------+--------------+
| PlayerName | PlayerStatus |
+------------+--------------+
| Chris      |            1 |
| David      |            0 |
| Sam        |            1 |
| Carol      |            1 |
| Bob        |            0 |
+------------+--------------+
5 rows in set (0.00 sec)

A seguir está a consulta para agrupar concat e colocar os dados em uma única linha com base nos valores 1 na coluna correspondente:

mysql> select group_concat(PlayerName) from DemoTable where PlayerStatus=1;

Isso produzirá a seguinte saída:

+--------------------------+
| group_concat(PlayerName) |
+--------------------------+
| Chris,Sam,Carol          |
+--------------------------+
1 row in set (0.00 sec)

Artigos relacionados: