Resultados MySQL como lista separada por comas
Necesito ejecutar una consulta como:
SELECT p.id, p.name,
(SELECT name
FROM sites s
WHERE s.id = p.site_id) AS site_list
FROM publications p
Pero me gustaría que la sub-selección devuelva una lista separada por comas, en lugar de una columna de datos. ¿Es esto posible, y si es así, cómo?
107
3 answers
Puede usar GROUP_CONCAT para realizar eso, por ejemplo, algo como
SELECT p.id, p.name, GROUP_CONCAT(s.name) AS site_list
FROM sites s
INNER JOIN publications p ON(s.id = p.site_id)
GROUP BY p.id, p.name;
221
Author: Paul Dixon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-19 19:31:13
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-19 19:31:13
En lugar de usar group concat()
puede usar solo concat()
Select concat(Col1, ',', Col2) as Foo_Bar from Table1;
Editar esto solo funciona en MySQL; Oracle concat solo acepta dos argumentos. En oracle puede usar algo como seleccionar col1||', ' / / col2//', ' / / col3 como foobar de tabla1; en sql Server usarías + en lugar de pipes.
8
Author: Robert Quinn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-12 20:33:25
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-12 20:33:25
En mi caso tengo que concatenar todo el número de cuenta de una persona cuyo número de móvil es único. Así que he utilizado la siguiente consulta para lograr eso.
SELECT GROUP_CONCAT(AccountsNo) as Accounts FROM `tblaccounts` GROUP BY MobileNumber
El resultado de la consulta es el siguiente:
Accounts
93348001,97530801,93348001,97530801
89663501
62630701
6227895144840002
60070021
60070020
60070019
60070018
60070017
60070016
60070015
2
Author: Vignesh Waran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-14 10:54:39
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-14 10:54:39