简体   繁体   中英

php mysql joining tables with concat

Can anyone help me with this?
I'm querying from 2 tables, country_table and language_table linked by country_id.

country_table:

country_id    continent      country  
 100          asia            china
 101          asia            japan
 102          europe          UK
 103          europe          germany  

language_table:

country_id    language_id     language
 100             01           mandarin  
 100             02           cantonese  
 102             03           english  
 102             04           french
 102             05           welsh          

What I want to achieved is to display all the countries with or without the language. If it has language, it should be concatenated just like the sample output below.

continent    country    language  
asia          china      mandarin, cantonese  
asia          japan      ----
europe        UK         english, french, welsh
europe        germany    ----  

You can use the GROUP_CONCAT() function to do the following:

select c.continent,
  c.country,
  group_concat(case 
               when l.language is null 
               then '----' else l.language end order by l.language) language
from country_table c
left join language_table l
  on c.country_id = l.country_id
group by c.continent, c.country

See SQL Fiddle with Demo

You need to do something like this.

SELECT ct.continent, ct.country, GROUP_CONCAT(lt.language)
FROM country_table ct
LEFT JOIN language_tabel lt USING(country_id)
GROUP BY ct.country

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM