8000 22 查找重复的电子邮箱 · Issue #27 · astak16/blog-mysql · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
22 查找重复的电子邮箱 #27
Open
@astak16

Description

@astak16

题目

查找 person 表中所有重复的电子邮箱

create table person (
	id int,
	email varchar(255)
);
insert into person values(1, 'a@b.com'), (2, 'c@d.com'), (3, 'a@b.com');

SQL:方法一

select email from person group by email having count(email) > 1;

解析

通过 group byemail 分组,在使用 having 将重复的 email 筛选出来。

SQL:方法二

select t.email from (
	select email, count(email) num from person group by email
) t where t.num > 1;

解析

email 分组后计算出相同 email 的数量作为临时表,筛选出 num > 1 的邮箱

SQL:方法三

with temp as (
	select email, count(email) num from person group by email
) 
select email from temp where num > 1;

解析

使用 with 建立临时表,和方法二一样

SQL:方法四

select distinct person.email from person
left join person temp on person.email = temp.email
where person.id != temp.id;

解析

使用 left join 自连,连接条件是 person.eamil = temp.email 并且通过 whereperson.id != temp.id筛选出来,最后再通过 distinct 去重

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0