删除语句 – p1 附近的语法不正确

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

Delete statement - incorrect syntax near p1

问题

我正在尝试解决来自 leetcode 的这个问题。

我编写了以下查询:

delete from person p1
where not exists
(
    select p2.email, min(p2.id)
    from person p2
    group by p2.email
    having min(p2.id) = p1.id
)

但我遇到了错误:

[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near 'p1'. (102) (SQLExecDirectW)

为什么会出现这个错误?

英文:

I am trying to solve this question from leetcode.

I wrote my query as below:

delete from person p1
where not exists
(
    select p2.email,min(p2.id)
    from person p2
    group by p2.email
    having min(p2.id)=p1.id
)

But I am getting the error:
>[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near 'p1'. (102) (SQLExecDirectW)

Why am I getting this error?

答案1

得分: 2

错误消息非常明确(错误语法),你不必为要删除的表创建别名。

delete from person
where not exists
(
    select p2.email, min(p2.id)
    from person p2
    group by p2.email
    having min(p2.id) = person.id
)
英文:

the error message was very clear(error syntax), you don't have to make alias for table you want to delete.

delete from person
where not exists
(
    select p2.email,min(p2.id)
    from person p2
    group by p2.email
    having min(p2.id)=person.id
)

答案2

得分: 1

这是另一种方法来执行操作:

 person 表中删除
其中 id  (
  选择 max(id) as id
   person 表中
   email 分组
   count(1) > 1
);

首先,您需要通过 group byhaving count > 1 获取重复的电子邮件,然后从该列表中获取 max(id)(最后添加的电子邮件),然后将其移除。

演示在这里

英文:

This is an other way to do it :

delete from person
where id in (
  select max(id) as id
  from person
  group by email
  having count(1) > 1
);

You first need to get the duplicated email by a group by and having count > 1, from this list we get the max(id) (the last added email)
Then we remove it.

Demo here

huangapple
  • 本文由 发表于 2023年2月16日 15:17:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75468933.html
匿名

发表评论

匿名网友

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

确定