mysql 多子查询 group_concat 查询

Posted

技术标签:

【中文标题】mysql 多子查询 group_concat 查询【英文标题】:mysql multiple-subquery group_concat query 【发布时间】:2011-04-28 14:16:08 【问题描述】:

我正在尝试显示特定城镇所在的行政区和邮政编码。

我的数据库结构相当好,有一个表格,例如城镇、邮政编码和自治市镇。 town_postcode 和 town_borough 的每个关系也有表格。

理想情况下,我希望数据返回为:

“艾比伍德”、“SE2”、“贝克斯利,格林威治” “巴比肯”、“EC1、EC2”、“伦敦金融城”

我尝试了几种不同的方法,我已经接近但还没有。

任何帮助将不胜感激... :) 到目前为止我已经尝试过

SELECT DISTINCT t.town, 
GROUP_CONCAT( DISTINCT p.postcode SEPARATOR ', ' ) AS 'postcode', 
GROUP_CONCAT( DISTINCT b.borough SEPARATOR ', ' ) AS 'borough'
FROM coverage_towns AS t, 
coverage_boroughs AS b, 
coverage_postcodes AS p, 
coverage_towns_boroughs AS tb, 
coverage_towns_postcodes AS tp
WHERE t.id = tp.town_id
AND p.id = tp.postcode_id
AND b.id = tb.borough_id
GROUP BY t.town
ORDER BY t.town ASC

返回

"Abbey Wood", "SE2", "Southwark, Hammersmith and Fulham, Tower Hamlets, Wandsworth, Enfield, Newham, LOTS MORE HERE"
"Barbican", "EC1, EC2", "Brent, Greenwich, Kensington and Chelsea, Westminster, Camden, LOTS MORE HERE"

我也试过

SELECT DISTINCT t.town, (

SELECT SQL_CACHE DISTINCT GROUP_CONCAT( p1.postcode
SEPARATOR ', ' )
FROM coverage_postcodes AS p1
WHERE p1.id = tp.postcode_id
) AS 'postcode', (

SELECT SQL_CACHE DISTINCT GROUP_CONCAT( b1.borough
SEPARATOR ', ' )
FROM coverage_boroughs AS b1
WHERE b1.id = tb.borough_id
) AS 'borough'
FROM coverage_towns AS t, coverage_boroughs AS b, coverage_postcodes AS p, coverage_towns_boroughs AS tb, coverage_towns_postcodes AS tp
WHERE t.id = tp.town_id
AND p.id = tp.postcode_id
AND b.id = tb.borough_id
GROUP BY t.town
ORDER BY t.town ASC

返回

"Abbey Wood", "SE2", "Greenwich"
"Acton", "W3", "Greenwich"
"Alders***", "E12", "Greenwich"

【问题讨论】:

【参考方案1】:

第一个查询看起来不错,只需在group_concat 内添加distinct,例如:

SELECT  t.town
,      GROUP_CONCAT(DISTINCT p.postcode SEPARATOR ', ' ) AS 'postcode'
,      GROUP_CONCAT(DISTINCT b.borough SEPARATOR ', ' ) AS 'borough'
<more code here>
GROUP BY
        t.town

【讨论】:

这当然是对第 2 列的改进,但现在我得到了“Abbey Wood”、“SE2”、“Southwark、Hammersmith 和 Fulham、Tower Hamlets、Wandsworth、Enfield、Newham,这里还有很多”“Barbican ", "EC1, EC2", "布伦特, 格林威治, 肯辛顿和切尔西, 威斯敏斯特, 卡姆登, 这里还有很多" 我正在寻找的地方: "Abbey Wood", "SE2", "Bexley, Greenwich" "Barbican", “EC1、EC2”、“伦敦金融城” @user482957:您在where 子句中缺少tbt 之间的链接【参考方案2】:

解决方案

喝了一杯好咖啡后,我回到了这个问题,答案就出来了。

SELECT DISTINCT t.town, 
GROUP_CONCAT( DISTINCT p.postcode SEPARATOR ', ' ) AS 'postcode', 
GROUP_CONCAT( DISTINCT b.borough SEPARATOR ', ' ) AS 'borough'
FROM towns AS t, boroughs AS b, postcodes AS p, towns_boroughs AS tb, towns_postcodes AS tp
WHERE (t.id = tp.town_id AND t.id = tb.town_id)
AND (p.id = tp.postcode_id AND b.id = tb.borough_id)
GROUP BY t.town
ORDER BY t.town ASC

【讨论】:

以上是关于mysql 多子查询 group_concat 查询的主要内容,如果未能解决你的问题,请参考以下文章

mysql查询结果拼接group_concat

mysql用GROUP_CONCAT合并查询出现乱码?求大神!!!

mysql GROUP_CONCAT 查询某个字段(查询结果默认逗号拼接)

mysql 分组查询问题 group_concat

如何使用 GROUP_CONCAT 正确地将 MySQL 查询转换为 MSSQL 查询

在 MySQL 中的子查询上使用 GROUP_CONCAT