简体   繁体   中英

join with GROUP_CONCAT

I have 3 tables in my database. I connect tables "persons"-"domains"-> id_person. Tables "domains"-"email"-> id.domain.

  • persons
  • domains
  • email
SELECT 
    p.id, 
    p.name, 
    GROUP_CONCAT(e.adres_email ORDER BY d.domain_end SEPARATOR '<hr>') AS adres_email, 
    GROUP_CONCAT(d.domain_name ORDER BY e.adres_email SEPARATOR '<hr>') AS domain_names, 
    GROUP_CONCAT(DISTINCT d.domain_end ORDER BY e.adres_email SEPARATOR '<hr>') AS domain_ends
FROM 
    domains d
    LEFT JOIN persons p ON d.id_person = p.id
    JOIN email e ON d.id=e.id_domain
GROUP BY 
    p.id

Problem, when domain doesn't have a e-mail adres and when domain have more email address, because i score double domain name

SELECT 
    p.id, 
    p.name, 
    GROUP_CONCAT(e.adres_email ORDER BY d.domain_end SEPARATOR '<hr>') AS adres_email, 
    GROUP_CONCAT(d.domain_name ORDER BY e.adres_email SEPARATOR '<hr>') AS domain_names, 
    GROUP_CONCAT(DISTINCT d.domain_end ORDER BY e.adres_email SEPARATOR '<hr>') AS domain_ends
FROM 
    domains d
    LEFT JOIN persons p ON d.id_person = p.id
    LEFT JOIN email e ON e.id = (SELECT id FROM email WHERE id_domain = d.id LIMIT 1)
GROUP BY 
    p.id, d.id

this query should do it.

The quick-and-dirty way is to use DISTINCT for all three:

SELECT p.id, p.name, 
       GROUP_CONCAT(DISTINCT e.adres_email ORDER BY d.domain_end SEPARATOR '<hr>') AS adres_email, 
       GROUP_CONCAT(DISTINCT d.domain_name ORDER BY e.adres_email SEPARATOR '<hr>') AS domain_names, 
       GROUP_CONCAT(DISTINCT d.domain_end ORDER BY e.adres_email SEPARATOR '<hr>') AS domain_ends
FROM persons p LEFT JOIN
     domains d 
     ON d.id_person = p.id LEFT JOIN
     email e
     ON d.id = e.id_domain
GROUP BY p.id;

I'm not 100% sure the ORDER BY s will work. They don't actually make that much sense to me.

Note that the LEFT JOIN s start with persons , not domains . That seems to be the intent of your query.

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