mysql多子查询group_concat查询

时间:2010-10-21 12:27:09

标签: mysql subquery group-concat

我正在尝试向自治市镇展示一个特定的城镇。

我的数据库结构合理,有一个表,如城镇,邮政编码和自治市镇。每个关系也有表格town_postcode& town_borough。

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

“Abbey Wood”,“SE2”,“Bexley,Greenwich” “Barbican”,“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"

2 个答案:

答案 0 :(得分:1)

第一个查询看起来不错,只需在distinct中添加group_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

答案 1 :(得分:1)

<强>解

我喝完好咖啡后又回到了问题,答案就出现了。

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