MySQL加入分组没有完美加入
MySQL joining with grouping did not join perfectly
我有三个 table 并想加入他们,但是当使用联系人 table 的父 ID 分组时,多次加入 returns 单行。
contact
table-
id
Name
1
Murad
2
Tajharul
phone
table-
id
contact_id
phone
1
1
017
2
2
014
3
2
015
email
table-
id
contact_id
email
1
1
mur@test.com
2
1
has@test.com
3
1
tan@test.com
4
2
taj@test.com
5
2
har@test.com
期望的输出-
id
Name
Phone
Email
1
Murad
017
mur@test.com,has@test.com,tan@test.com
2
Tajharul
014,015
taj@test.com,har@test.com
这是我到目前为止尝试过的-
SELECT contact.name , GROUP_CONCAT(phone.phone) phone, GROUP_CONCAT(email.email) email
FROM
contact
JOIN phone ON contact.id = phone.contact_id
JOIN email ON contact.id = email.contact_id
GROUP BY contact.id
MySQL Fiddle link: http://sqlfiddle.com/#!9/ded29f/1
在 group_concat
中使用 DISTINCT
SELECT contact.name , GROUP_CONCAT(DISTINCT phone.phone) phone, GROUP_CONCAT(DISTINCT email.email) email
FROM
contact
JOIN phone ON contact.id = phone.contact_id
JOIN email ON contact.id = email.contact_id
GROUP BY contact.id
您可以通过在 Group concat 中使用子查询和 Distinct 来实现:
SELECT T1.id, T1.name, T1.phone, GROUP_CONCAT(DISTINCT email.email) email
FROM
(SELECT contact.id, contact.name , GROUP_CONCAT(DISTINCT phone.phone) phone
FROM
contact
JOIN phone ON contact.id = phone.contact_id
GROUP BY contact.id) T1
JOIN email ON T1.id = email.contact_id
GROUP BY T1.id
我有三个 table 并想加入他们,但是当使用联系人 table 的父 ID 分组时,多次加入 returns 单行。
contact
table-
id | Name |
---|---|
1 | Murad |
2 | Tajharul |
phone
table-
id | contact_id | phone |
---|---|---|
1 | 1 | 017 |
2 | 2 | 014 |
3 | 2 | 015 |
email
table-
id | contact_id | |
---|---|---|
1 | 1 | mur@test.com |
2 | 1 | has@test.com |
3 | 1 | tan@test.com |
4 | 2 | taj@test.com |
5 | 2 | har@test.com |
期望的输出-
id | Name | Phone | |
---|---|---|---|
1 | Murad | 017 | mur@test.com,has@test.com,tan@test.com |
2 | Tajharul | 014,015 | taj@test.com,har@test.com |
这是我到目前为止尝试过的-
SELECT contact.name , GROUP_CONCAT(phone.phone) phone, GROUP_CONCAT(email.email) email
FROM
contact
JOIN phone ON contact.id = phone.contact_id
JOIN email ON contact.id = email.contact_id
GROUP BY contact.id
MySQL Fiddle link: http://sqlfiddle.com/#!9/ded29f/1
在 group_concat
中使用 DISTINCTSELECT contact.name , GROUP_CONCAT(DISTINCT phone.phone) phone, GROUP_CONCAT(DISTINCT email.email) email
FROM
contact
JOIN phone ON contact.id = phone.contact_id
JOIN email ON contact.id = email.contact_id
GROUP BY contact.id
您可以通过在 Group concat 中使用子查询和 Distinct 来实现:
SELECT T1.id, T1.name, T1.phone, GROUP_CONCAT(DISTINCT email.email) email
FROM
(SELECT contact.id, contact.name , GROUP_CONCAT(DISTINCT phone.phone) phone
FROM
contact
JOIN phone ON contact.id = phone.contact_id
GROUP BY contact.id) T1
JOIN email ON T1.id = email.contact_id
GROUP BY T1.id