Skip to content

Commit 6f334e0

Browse files
committed
Add solution 196 [sql]
group by min not in
1 parent bb4a5df commit 6f334e0

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ Complete [solutions](https://github.com/doocs/leetcode/tree/master/solution) to
4040
| 182 | [Duplicate Emails](https://github.com/doocs/leetcode/tree/master/solution/182.Duplicate%20Emails) | `SQL` |
4141
| 183 | [Customers Who Never Order](https://github.com/doocs/leetcode/tree/master/solution/183.Customers%20Who%20Never%20Order) | `SQL` |
4242
| 189 | [Rotate Array](https://github.com/doocs/leetcode/tree/master/solution/189.Rotate%20Array) | `Array` |
43+
| 196 | [Delete Duplicate Emails](https://github.com/doocs/leetcode/tree/master/solution/196.Delete%20Duplicate%20Emails) | `SQL` |
4344
| 198 | [House Robber](https://github.com/doocs/leetcode/tree/master/solution/198.House%20Robber) | `Dynamic Programming` |
4445
| 203 | [Remove Linked List Elements](https://github.com/doocs/leetcode/tree/master/solution/203.Remove%20Linked%20List%20Elements) | `Linked List` |
4546
| 231 | [Power of Two](https://github.com/doocs/leetcode/tree/master/solution/231.Power%20of%20Two) | `Math`, `Bit Manipulation` |
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
## 删除重复的电子邮箱
2+
### 题目描述
3+
4+
5+
编写一个 SQL 查询,来删除 `Person` 表中所有重复的电子邮箱,重复的邮箱里只保留 **Id** 最小 的那个。
6+
```
7+
+----+------------------+
8+
| Id | Email |
9+
+----+------------------+
10+
11+
12+
13+
+----+------------------+
14+
Id 是这个表的主键。
15+
```
16+
17+
例如,在运行你的查询语句之后,上面的 `Person` 表应返回以下几行:
18+
```
19+
+----+------------------+
20+
| Id | Email |
21+
+----+------------------+
22+
23+
24+
+----+------------------+
25+
```
26+
27+
### 解法
28+
先根据 `Email` 分组,选出每个组中最小的 `Id`,作为一张临时表,再删除掉所有 Id 不在这张临时表的记录。
29+
30+
```sql
31+
# Write your MySQL query statement below
32+
33+
# 用这里注释的语句运行会报错,不能 select 之后再 update
34+
# You can't specify target table 'Person' for update in FROM clause
35+
# delete from Person
36+
# where Id not in(
37+
# select min(Id) as Id
38+
# from Person
39+
# group by Email);
40+
41+
delete from Person
42+
where Id not in(
43+
select Id from (
44+
select min(id) as Id
45+
from Person
46+
group by Email
47+
) a
48+
);
49+
```
50+
51+
#### Input
52+
```json
53+
{"headers": {"Person": ["Id", "Email"]}, "rows": {"Person": [[1, "[email protected]"], [2, "[email protected]"], [3, "[email protected]"]]}}
54+
```
55+
56+
#### Output
57+
```json
58+
{"headers":["Id","Email"],"values":[[1,"[email protected]"],[2,"[email protected]"]]}
59+
```

0 commit comments

Comments
 (0)