0

我被困在这个查询上:我想更新临时表#tmpHierarchy 中的每一行并设置 pLevel = 3,如果该行尚未设置级别(= 99)并且其中一个 [可能] 父项包含在临时表,级别 = 2。

表 items 包含所有项目,表 ParentItems 包含 Items 之间的链接(字段 Item、ParentItem)

就像是:

UPDATE #tmpHierarchy SET pLevel = 3 WHERE pLevel = 99 
      AND (
               (
               SELECT Item FROM Items as IT LEFT JOIN ParentItems as PTS ON PTS.ItemID = IT.ID 
                             WHERE IT.ID = #tmpHierarchy.ItemID
                ) 
           IN
               (
               SELECT Item FROM #tmpHierarchy WHERE pLevel = 2
               )
           )

这将是我想要实现的目标,但它会返回

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has been terminated.

...由于显而易见的原因,我在 IN 子句 (?) 中有多个值。

我很高兴得到一些关于这个问题的建议。

问候,

橡木

4

3 回答 3

1

我很确定问题出在查询的那一部分:

SELECT Item FROM Items as IT LEFT JOIN ParentItems as PTS ON PTS.ItemID = IT.ID 
                         WHERE IT.ID = #tmpHierarchy.ItemID

它返回不止一行,并且您可以与 IN 子句不允许进行多对多比较。

您可以将查询更改为以下内容:

UPDATE  #tmpHierarchy
SET     pLevel = 3
WHERE   pLevel = 99
        AND EXISTS ( SELECT Item
                     FROM   Items AS IT
                            LEFT JOIN ParentItems AS PTS ON PTS.ItemID = IT.ID
                     WHERE  IT.ID = #tmpHierarchy.ItemID
                            AND Item IN ( SELECT    Item
                                          FROM      #tmpHierarchy
                                          WHERE     pLevel = 2 ) );
于 2015-10-07T17:34:07.240 回答
1

如果使用 IN,左子查询必须是“一行”结果,试试这个:

UPDATE #tmpHierarchy SET pLevel = 3 WHERE pLevel = 99 
      AND (
            SELECT Item 
            FROM ParentItems as PTS WHERE PTS.ItemID = #tmpHierarchy.ItemID AND
                   #tmpHierarchy.pLevel = 2
           ) IS NOT NULL

我假设该项目是 ParentItems。

这是我对网站的第一次评论,任何提示或投诉都可以随意做。

编辑:现在我明白了,因为 SELECT ... pLevel = 99 ...(#tmpHierarchy.pLevel = 2 是不可能的),由所有者在 EXISTS 中具有正确的连接来解决。

于 2015-10-07T17:52:04.823 回答
0

好的,所以将第二个条件修改为 INNER JOIN 似乎会给出正确的结果:

              AND EXISTS (
                         SELECT ParItem.ID
                         FROM Items as IT
                         LEFT JOIN ParentItems as PTS ON PTS.ItemID = IT.ID 
                         LEFT JOIN Items as ParItem on ParItem.ID = PTS.ParentItemID
                         INNER JOIN #tmpHierarchy as H ON H.ItemID = ParItem.ID 
                         WHERE IT.ItemID = HI.PartNo AND H.pLevel = 2
                         )

希望对以后的观众有所帮助。

问候橡树

于 2015-10-07T18:09:43.857 回答