如何在MS SQL WHERE IN中删除(选择多列)

时间:2013-05-24 12:33:46

标签: sql sql-server-2008

我有一个表格,可以将其称为“Cluster”,这与第二张表Element

相关

集群:

Id Group Ele1 Ele2 Ele3
1   1     1    2     3
2   1     4   NULL   9
3   2     5    8     7

元素

Id Name
1  'A'
2  'b'
3  'c'
4  'd'
5  'z'
6  'j'
7  't'
8  'r'
9  'e'

现在我必须删除群集

DELETE FROM Cluster
WHERE   Cluster.Group= 1

但在我从Cluster删除行之前,我需要删除Element

中的所有相关行
DELETE FROM Element
WHERE Id IN (SELECT Ele1 Ele2 Ele3 
             FROM Cluster 
             WHERE Cluster.Group= 1)

但是这个查询不起作用,所以我错过了什么?

7 个答案:

答案 0 :(得分:4)

试试这个:

DELETE FROM Element
WHERE Id IN (SELECT Ele1
             FROM Cluster 
             WHERE Cluster.[Group] = 1
                   And Ele1 Is Not NULL

             Union 

             SELECT Ele2
             FROM Cluster 
             WHERE Cluster.[Group] = 1
                   And Ele2 Is Not NULL

             Union 

             SELECT Ele3 
             FROM Cluster 
             WHERE Cluster.[Group] = 1
                   And Ele3 Is Not NULL
)

答案 1 :(得分:3)

紧凑而干净:

DELETE FROM Element
WHERE Id IN (
    SELECT
        Ele
    FROM Cluster AS T
    CROSS APPLY (VALUES
        (T.Ele1)
        , (T.Ele2)
        , (T.Ele3)
    ) AS X (Ele)
    WHERE T.Group= 1
)

答案 2 :(得分:1)

<强>已更新

delete  from Element
where ID in
(
SELECT Item
   FROM 
      (SELECT [Group], Ele1, cast([Ele2] as int) Ele2, Ele3 FROM Cluster) p
   UNPIVOT(Item FOR Ele IN (Ele1, Ele2, Ele3) )AS unpvt
  )

答案 3 :(得分:1)

有几个有效的解决方案,但我没有看到任何解释为什么它们有效并且你的尝试失败。

IN运算符需要检查值列表。最简单的看起来像WHERE column IN (value1, value2, value3...)。它也适用于SELECT列表:WHERE column IN (SELECT somecolumn FROM sometable)

您的查询不返回可用作列表的单个列,而是返回三个不同的列。这是IN运算符的错误语法。 G Mastros的解决方案使用UNION运算符将三个不同的选择查询组合在一个单列结果集中。

(在这种情况下,我会使用UNION ALL,因为重复的值不是问题而且UNION是一个较慢的操作。但检查您的客户端统计信息,因为检查值的多个副本可能是比UNION)更多的性能消耗

StuffHappens使用UNPIVOT运算符来获得将三个必需列拆分为单个结果集的相同行为。就个人而言,我会选择UNION,主要是因为我发现UNPIVOT语法难以理解。

答案 4 :(得分:1)

将表规范化为不具有多列是最佳答案。

鉴于您现有的桌面设计,G Mastro的答案非常好。

它看起来如何规范......所以你可以这样做:

delete from Element 
where Id in ( select EleId from  GroupElements where Group_id = 1 )


*Cluster* 

Id Group
1   1   
2   1   
3   2   

*GroupElements*

Group_id EleId
1   1
1   2
1   3
1   4
1   9
2   5
2   8
2   7


*Element*

Id Name
1  'A'
2  'b'
3  'c'
4  'd'
5  'z'
6  'j'
7  't'
8  'r'
9  'e'

答案 5 :(得分:0)

DELETE FROM Element
WHERE Id IN (SELECT Ele1
         FROM Cluster 
         WHERE Cluster.Group= 1) AND Id IN (SELECT Ele2
         FROM Cluster 
         WHERE Cluster.Group= 1) AND Id IN (SELECT Ele3
         FROM Cluster 
         WHERE Cluster.Group= 1)

答案 6 :(得分:-1)

您没有在子查询中从Cluster中选择ID列。尝试:

DELETE FROM Element
WHERE Id IN (SELECT Id 
         FROM Cluster 
         WHERE Cluster.Group= 1)