[英]MySQL GROUP_CONCAT and Multiple Lookup Tables
我有七個要加入的表格:
Table programs
Column id program_name program_description
1 Self Help Self Help Description...
2 Wellness Wellness Description...
3 Education Education Description...
______________________________________________________
Table county
Column id county_name
1 Stark
2 Portage
3 Wayne
_________________________
Table services
Column id service_name service_description
1 Counseling Counseling Description...
2 Group Therapy Group Therapy Description...
3 Evaluation Evaluation Description...
__________________________________________________________
Table population
Column id population_name
1 Adults
2 Children
3 Youth
_____________________________
Table program_county
Column id program_id county_id
1 1 2
2 1 3
3 2 1
4 2 2
_____________________________________
Table program_service
Column id program_id service_id
1 1 2
2 1 3
3 2 1
4 2 2
5 2 3
______________________________________
Table program_population
Column id program_id population_id
1 1 3
2 2 1
3 2 3
4 3 1
_________________________________________
我正在嘗試編寫一個查詢,該查詢將為每個程序返回一行,並在program_county,program_services和program_population表中檢索相關的行,並查找這些服務的名稱,人口和縣將它們分別顯示在一個字段中。 喜歡:
id program_name program_description Counties Services Population Served
1 Self Help Self Help Description... Portage, Wayne Group Therapy, Evaluation Youth
2 Wellness Wellness Description Stark, Portage Counseling, Group Therapy, Evaluation Adults, Youth
我知道我必須使用聯接和GROUP_CONCAT,但是我很失落。
如果要查看所有程序,而不管它們是與縣,服務還是人口相關聯,就需要使用外部聯接。 同樣,您應該在要連接的值周圍使用coalesce()
以正確處理NULL值。
這樣的事情應該起作用:
select programs.id, programs.program_name, programs.program_description,
group_concat(distinct coalesce(county.county_name,'')) as "Counties",
group_concat(distinct coalesce(services.service_name,'')) as "Services",
group_concat(distinct coalesce(population.population_name,'')) as "Population Served"
from programs
left outer join program_county on program_county.program_id = programs.id
left outer join county on county.id = program_county.county_id
left outer join program_service on program_service.program_id = programs.id
left outer join services on services.id = program_service.service_id
left outer join program_population on program_population.program_id = programs.id
left outer join population on population.id = program_population.population_id
group by programs.id, programs.program_name, programs.program_description
order by programs.id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.