问题
I have a series of complicated MySQL select queries / joins that produce results similar to this:
|----|---------|----------|----------|---------------|---------------|
| id | company | city | province | manager_email | staff_email |
|----|---------|----------|----------|---------------|---------------|
| 1 | aaa | toronto | ON | john@aaa.com | |
| 1 | aaa | toronto | ON | | smith@aaa.com |
| 2 | bbb | sudbury | ON | john@bbb.com | |
| 3 | ccc | hamilton | ON | john@ccc.com | |
| 3 | ccc | hamilton | ON | | smith@ccc.com |
|----|---------|----------|----------|---------------|---------------|
- most "companies" have two rows, which are identical other than the emails
manager_email
andstaff_email
will never appear in the same row- there are some cases where a "company" will only have one row
Is there a GROUP BY
or a similar statement that I can use to group all of these duplicate rows, while retaining both emails? e.g.
|----|---------|----------|----------|---------------|---------------|
| id | company | city | province | manager_email | staff_email |
|----|---------|----------|----------|---------------|---------------|
| 1 | aaa | toronto | ON | john@aaa.com | smith@aaa.com |
| 2 | bbb | sudbury | ON | john@bbb.com | |
| 3 | ccc | hamilton | ON | john@ccc.com | smith@ccc.com |
|----|---------|----------|----------|---------------|---------------|
I'm willing to share more details if needed, but at this point I think it'll just add confusion.
回答1:
You can take advantage of the fact that most aggregate functions ignore null
:
select
id,
company,
city,
province,
max(manager_email) manager_email,
max(staff_email) staff_email
from mytable
group by id, company, city, province
来源:https://stackoverflow.com/questions/58957478/mysql-group-multiple-rows-while-retaining-differences