简体   繁体   中英

MySql: select unique values

I have a table with a column named 'emails'. I need a query that selects the emails that only appears once in the table.

So when the column 'emails' has (a@mail.com, a@mail.com, b@mail.com) I just want to select b@company.com.

I have tried the following query:

SELECT DISTINCT `emails` FROM `table`

But the problem is that it selects a@mail.com and b@mail.com.

I need a query what will only select b@mail.com.

Can anyone help me?

You can use the following

select 
count(*) as cnt,
email from table 
group by email having cnt = 1 

If you have an auto-incremented primary key then you have other approach as well something as

select * from table t1
where not exists (
 select 1 from table t2
 where t1.email = t2.email
 and t1.id <> t2.id
);

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