我試圖顯示自治市鎮和郵編是在一個特定的城鎮。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"
這肯定對the2nd列的改善,但現在我得到 「修道院木」,「SE2」,「南華,哈默史密斯和富勒姆,倫敦塔橋,旺茲沃思,恩菲爾德,紐漢,其它更多的HERE」 「 Barbican「,」EC1,EC2「,」布倫特,格林威治,肯辛頓和切爾西,威斯敏斯特,卡姆登,更多這裏「 我在尋找: 」Abbey Wood「,」SE2「,」Bexley,Greenwich 「 」Barbican「,」EC1,EC2「,」倫敦金融城「 – user482957 2010-10-21 13:07:14
@ user482957:您錯過了'where'子句中'tb'和't'之間的鏈接 – Andomar 2010-10-21 13:46:40