4

我有一张桌子,我们称之为“ 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)

但是这个查询不起作用所以我想念什么?

4

7 回答 7

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
)
于 2013-05-24T12:40:41.317 回答
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
)
于 2013-05-24T13:14:02.577 回答
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语法更难理解。

于 2013-05-24T13:03:28.687 回答
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'
于 2013-05-24T13:17:38.313 回答
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
  )
于 2013-05-24T12:52:28.330 回答
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)
于 2013-05-24T12:41:55.947 回答
-1

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

DELETE FROM Element
WHERE Id IN (SELECT Id 
         FROM Cluster 
         WHERE Cluster.Group= 1)
于 2013-05-24T12:37:40.820 回答