2014-12-01 66 views

回答

2

您可以使用group_concat

select 
city_name, 
group_concat(user_names) as user_names 
from table_name 
group by city_name 
+0

此功能使用'“”'作为‘胶水’,所以如果我需要别的东西胶水 - 我会在深SHT不可开交。如果根本没有默认胶水会更好,因为我可以使用'group_concat(concat(user_name,'my glue'))''。有什么我可以用“胶水”做的事情吗? – 2014-12-01 19:20:54

+1

阅读该函数的手册页。你可以指定任何你想要的胶水字符。 – 2014-12-01 19:24:55

+1

是的,你可以使用'group_concat(名字SEPARATOR'||')'..添加你想要的任何SEPARATOR。 – 2014-12-01 19:24:57

0

SQL Fiddle

MySQL的32年5月5日架构设置

CREATE TABLE Table1 
    (`name` varchar(6), `city` varchar(8)) 
; 

INSERT INTO Table1 
    (`name`, `city`) 
VALUES 
    ('John', 'New York'), 
    ('Aaron', 'New York'), 
    ('George', 'Dallas'), 
    ('Low', 'Dallas'), 
    ('John', 'Dallas'), 
    ('Young', 'Dallas') 
; 

查询1

select 
concat('[''',city,'''] => ''',group_concat(name),'''') as array 
from table1 
group by city 

Results

|         ARRAY | 
|---------------------------------------| 
| ['Dallas'] => 'George,Low,John,Young' | 
|   ['New York'] => 'John,Aaron' | 
+0

对不起,我没有那么清楚:我不是说结果应该直接来自MySQL。 – 2014-12-01 19:25:13

+0

但是,您在MySQL语法中“模拟”PHP数组外观的努力令人印象深刻! – 2014-12-01 19:29:56