比方说,我有一个包含用户名和城市的表:我可以从MySQL DB中获取多个字符串作为单个“粘贴”字符串吗?
- 约翰|纽约
- Aaron |纽约
- George |达拉斯
- 低|达拉斯
- John |达拉斯
- 年轻|达拉斯
而且我希望有一个数组,如下所示:
['New York'] => 'John, Aaron',
['Dallas'] => 'George, Low, John, Young'
所以我想我需要连接组操作员中的字符串。
有没有解决方法?
比方说,我有一个包含用户名和城市的表:我可以从MySQL DB中获取多个字符串作为单个“粘贴”字符串吗?
而且我希望有一个数组,如下所示:
['New York'] => 'John, Aaron',
['Dallas'] => 'George, Low, John, Young'
所以我想我需要连接组操作员中的字符串。
有没有解决方法?
您可以使用group_concat
select
city_name,
group_concat(user_names) as user_names
from table_name
group by city_name
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
| ARRAY |
|---------------------------------------|
| ['Dallas'] => 'George,Low,John,Young' |
| ['New York'] => 'John,Aaron' |
对不起,我没有那么清楚:我不是说结果应该直接来自MySQL。 – 2014-12-01 19:25:13
但是,您在MySQL语法中“模拟”PHP数组外观的努力令人印象深刻! – 2014-12-01 19:29:56
此功能使用'“”'作为‘胶水’,所以如果我需要别的东西胶水 - 我会在深SHT不可开交。如果根本没有默认胶水会更好,因为我可以使用'group_concat(concat(user_name,'my glue'))''。有什么我可以用“胶水”做的事情吗? – 2014-12-01 19:20:54
阅读该函数的手册页。你可以指定任何你想要的胶水字符。 – 2014-12-01 19:24:55
是的,你可以使用'group_concat(名字SEPARATOR'||')'..添加你想要的任何SEPARATOR。 – 2014-12-01 19:24:57