LeetCode笔记:(MySQL) 182. Duplicate Emails

Write a SQL query to find all duplicate emails in a table named Person.

+----+---------+
| Id | Email   |
+----+---------+
| 1  | a@b.com |
| 2  | c@d.com |
| 3  | a@b.com |
+----+---------+

For example, your query should return the following for the above table:

+---------+
| Email   |
+---------+
| a@b.com |
+---------+

Note: All emails are in lowercase.


My Solution:

SELECT DISTINCT
    person1.Email
FROM
    person person1
INNER JOIN person person2 ON person1.email = person2.email
WHERE
    person1.id <> person2.id

思路:

先用inner join拼接Person表中含有相同Email的所有id,然后再使用DISTINCT关键字去除重复的记录。(性能较低,倒数12%)


Other People’s Solutions:

SELECT
    Email
FROM
    Person
GROUP BY
    Email
HAVING
    count(*) > 1

摘自 —— https://discuss.leetcode.com/topic/7485/i-have-this-simple-approach-anybody-has-some-other-way
作者:dashinghimay

OR

SELECT DISTINCT
    Email
FROM
    Person
HAVING
    count(*) > 1

思路:

先查询出所有不重复的Email,再使用count()函数对结果进行筛选,最终筛选出次数大于一次的所有Email

注意:

(使用GROUP BY可以限制查询结果中某一个字段不重复,而使用DISTINCT则为限制查询结果中所有字段同时不重复)
例:

 1.此处查询的是Id及Email字段,可以仅限制Email字段不重复。
SELECT Id, Email
FROM Person
GROUP BY Email DESC
 2.此处查询的也是Id及Email字段,但限制为Id及Email字段同时不重复。
SELECT DISTINCT Id, Email
FROM Person

拓展:

HAVING 子句
在 SQL 中增加 HAVING 子句原因是,WHERE 关键字无法与合计函数一起使用

SQL HAVING 子句 —— W3School
http://www.w3school.com.cn/sql/sql_having.asp

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值