简体   繁体   中英

How to keep one row for each unique column value after groupby in MySQL?

I have a column of ids and a column of emails. I would like to group by id and only keep rows with distinct emails (it can be any row). For example:

+-------------------------------+
|    Id          Email          |
+-------------------------------+
|    1         email1           |
|    1         email2           |
|    1         email1           |
|    2         email3           |
|    2         email3           |
|    3         email4           |
|    3         email4           |
+-------------------------------+

The final output would be:

+---------------------------+
| Id            Email       |
+---------------------------+
| 1        email1           |
| 1        email2           |
| 2        email3           |
| 3        email4           |
+---------------------------+

The idea is something like

SELECT * FROM table
GROUP BY Id
HAVING DISTINCT(email)

but the syntax is not correct.

Any help would be appreciated. Thank you!

For this dataset, a simple select distinct should do:

select distinct id, email from mytable

This simply removes duplicate rows from the resultset, which seems to be what you are looking for.

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