2010-10-21 172 views
1

我试图显示自治市镇和邮编是在一个特定的城镇。mysql多重子查询group_concat查询

我的数据库结构很好,有一张表,如城镇,邮政编码和自治市镇。 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" 
"Aldersbrook", "E12", "Greenwich" 

回答

1

首先查询看起来不错,只需添加distinctgroup_concat内,如:

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 
+0

这肯定对the2nd列的改善,但现在我得到 “修道院木”,“SE2”,“南华,哈默史密斯和富勒姆,伦敦塔桥,旺兹沃思,恩菲尔德,纽汉,其它更多的HERE” “ Barbican“,”EC1,EC2“,”布伦特,格林威治,肯辛顿和切尔西,威斯敏斯特,卡姆登,更多这里“ 我在寻找: ”Abbey Wood“,”SE2“,”Bexley,Greenwich “ ”Barbican“,”EC1,EC2“,”伦敦金融城“ – user482957 2010-10-21 13:07:14

+1

@ user482957:您错过了'where'子句中'tb'和't'之间的链接 – Andomar 2010-10-21 13:46:40

1

SOLUTION

我又重新回到了问题的好咖啡后,答案提出了自己。

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