删除 select 语句中存在 column 的行

Posted

技术标签:

【中文标题】删除 select 语句中存在 column 的行【英文标题】:Remove rows where column exists in select statement 【发布时间】:2018-10-19 23:20:21 【问题描述】:

我想删除 select 语句中存在特定列的行,例如:

delete from [ProjectCustomer] pcc 
where ProjectKey in (
  select p.ProjectKey  
  FROM [Project] AS [p] inner JOIN [ProjectDesign] AS [pd] ON [p].[ProjectKey] = [pd].[ProjectKey]
  inner JOIN [Design] AS [d] ON [pd].[DesignKey] = [d].[DesignKey]
  inner JOIN [ProjectCustomer] AS [pc] ON [pc].[ProjectKey] = [p].[ProjectKey]
  inner join Customer as c on pc.CustomerKey = c.CustomerKey
  where d.Folio = 3014)

但是在 delete 语句的 where 子句中我得到了

where 子句附近的语法不正确

我做错了什么?问候

【问题讨论】:

您能否为上述查询添加足够的数据库架构以引用现有的表和列名?它可能会帮助我诊断您的问题。 应该是delete pcc from [ProjectCustomer] pcc 尝试删除 pcc 别名,因为您不使用它。 【参考方案1】:

具有表别名的 DELETE 语句具有不同的语法,因此您可以删除未使用的别名或更改删除语句,如 @Martin 评论。

delete pcc from [ProjectCustomer] pcc

我会准备使用INNER JOIN 而不是IN 来修改查询

delete pcc from [ProjectCustomer] AS pcc 
  inner join [Project] AS [p] ON [p].ProjectKey = [pcc].ProjectKey
  inner JOIN [ProjectDesign] AS [pd] ON [p].[ProjectKey] = [pd].[ProjectKey]
  inner JOIN [Design] AS [d] ON [pd].[DesignKey] = [d].[DesignKey]
  inner JOIN [ProjectCustomer] AS [pc] ON [pc].[ProjectKey] = [p].[ProjectKey]
  inner join Customer as c on pc.CustomerKey = c.CustomerKey
  where d.Folio = 3014)

【讨论】:

【参考方案2】:

我认为错误信息是

“pcc”附近的语法不正确

而不是

where 子句附近的语法不正确

您将收到第一条错误消息,因为您使用了错误的别名,所以当您没有加入目标表时,您可能需要

delete from [ProjectCustomer]
where ProjectKey in (
  select p.ProjectKey  
  FROM [Project] AS [p] inner JOIN [ProjectDesign] AS [pd] ON [p].[ProjectKey] = [pd].[ProjectKey]
  inner JOIN [Design] AS [d] ON [pd].[DesignKey] = [d].[DesignKey]
  inner JOIN [ProjectCustomer] AS [pc] ON [pc].[ProjectKey] = [p].[ProjectKey]
  inner join Customer as c on pc.CustomerKey = c.CustomerKey
  where d.Folio = 3014);

或者即使你仍然想使用别名

delete pcc from [ProjectCustomer] pcc
where pcc.ProjectKey in ...

【讨论】:

【参考方案3】:

您可能可以稍微简化您的查询。我认为您不需要子查询,您可以在第一个 FROM 子句中指定要从中删除的表(没有别名),然后在第二个中加入表(根据需要使用别名):

DELETE FROM ProjectCustomer
FROM ProjectCustomer pc
  INNER JOIN ProjectDesign pd ON pc.ProjectKey = pd.ProjectKey
    INNER JOIN Design d ON pd.DesignKey = d.DesignKey
WHERE d.Folio = 3014;

CustomersProducts 表不应该是必需的,只要您设置了参照完整性并且 pc.CustomerKey 不可为空。

【讨论】:

以上是关于删除 select 语句中存在 column 的行的主要内容,如果未能解决你的问题,请参考以下文章

c#怎么从dataset去除重复行

在DB2数据库中删除一组有限的行

如果 Column 存在,则删除列

MySQL WHERE LIKE 语句:如何删除表中列子字符串不等于所需子字符串的行?

INSERT INTO SELECT 语句

[22]SQL INSERT INTO SELECT 语句