从 SQL 表中消除重复的行。

huangapple go评论75阅读模式
英文:

Eliminate the duplicate rows from the table in SQL

问题

我想根据电子邮件地址从表格中消除重复的行,并检索所有没有重复的行。

我尝试使用DISTINCT,但我没有得到期望的结果。

SELECT 
  DISTINCT Email 
FROM 
  Users

示例表格

Id Email Username
1 sam@gmail.com sam1122
2 john@gmail.com john1122
3 sam@gmail.com sam2233
4 lily@gmail.com lily@as

我想要检索的内容

Id Email Username
1 john@gmail.com john1122
2 lily@gmail.com lily@as
英文:

I want to eliminate the duplicate rows based on email from the table and retrieve all the rows without duplicates.

I have tried using distinct but I'm not getting desired results.

SELECT 
  DISTINCT Email 
FROM 
  Users

Example Table:

Id Email Username
1 sam@gmail.com sam1122
2 john@gmail.com john1122
3 sam@gmail.com sam2233
4 lily@gmail.com lily@as

What I want to retrieve:

Id Email Username
1 john@gmail.com john1122
2 lily@gmail.com lily@as

答案1

得分: 1

我们可以尝试在这里使用存在性逻辑:

SELECT Id, Email, Username
FROM Users u1
WHERE NOT EXISTS (
    SELECT 1
    FROM Users u2
    WHERE u2.Email = u1.Email AND
          u2.Id <> u1.Id
);
英文:

We can try using exists logic here:

<!-- language: sql -->

SELECT Id, Email, Username
FROM Users u1
WHERE NOT EXISTS (
    SELECT 1
    FROM Users u2
    WHERE u2.Email = u1.Email AND
          u2.Id &lt;&gt; u1.Id
);

答案2

得分: 0

从用户中选择 Id、Email 和 Username
其中 Email 在 (
    从用户中选择 Email
    分组并且计数为 1
    )
英文:
SELECT Id, Email, Username
FROM Users
WHERE Email IN (
    SELECT Email
    FROM Users
    GROUP BY Email
    HAVING COUNT(*) = 1
)

答案3

得分: 0

你可以使用 left join 来实现:

select u.*
from Users u
left join (
  select email, max(id) as Id
  from Users
  group by email
  having count(1) > 1
) as s on s.email = u.email
where s.email is null;

在此查看示例

英文:

You can do it using left join :

select u.*
from Users u
left join (
  select email, max(id) as Id
  from Users
  group by email
  having count(1) &gt; 1
) as s on s.email = u.email
where s.email is null;

Demo here

答案4

得分: 0

以下是翻译的内容:

如果您正在使用MySQL 8,另一种选项是 -

SELECT Id, Email, Username
FROM (
    SELECT *, COUNT(*) OVER (PARTITION BY Email) AS cnt
    FROM Users
) t
WHERE t.cnt = 1;
英文:

Yet another option, if you are using MySQL 8 -

SELECT Id, Email, Username
FROM (
    SELECT *, COUNT(*) OVER (PARTITION BY Email) AS cnt
    FROM Users
) t
WHERE t.cnt = 1;

答案5

得分: -1

SELECT id,
   Email,
   Username,
   count(*) AS duplicate_email_count
FROM Users
GROUP BY Email
HAVING duplicate_email_count=1
英文:
SELECT id,
   Email,
   Username,
   count(*) AS duplicate_email_count
FROM Users
GROUP BY Email
HAVING duplicate_email_count=1

huangapple
  • 本文由 发表于 2023年2月8日 14:53:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75382272.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定