假设我有一个包含用户名和城市的表格:
我希望有一个数组如下:
['New York'] => 'John, Aaron',
['Dallas'] => 'George, Low, John, Young'
所以我认为我需要在GROUP运算符中连接字符串。
有没有解决方案?
答案 0 :(得分:2)
您可以使用 group_concat
select
city_name,
group_concat(user_names) as user_names
from table_name
group by city_name
答案 1 :(得分:0)
MySQL 5.5.32架构设置:
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' |