2014-12-01 28 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