简单的SQL select会重载我的服务器

时间:2018-01-05 20:34:26

标签: sql sql-server

问题是这个任务,虽然看起来容易挑战我的SQL Server所以我必须寻找一个更容易的。

我有表items(有300.000行)

item  
-----
10  
11  
13  
14  
15

然后我有表parent-Child(有900.000行)

Parent  Child
--------------
10      13
14      13
13      15

对于我想要找出的项目中的每一行

  1. 项目在Parent中至少有一次,而在Child中
  2. 项目位于Parent AND Child
  3. 项目位于Child,而不是Parent
  4. 既不是(好的 - 其余的......)
  5. 我想将相关案例a / b / c / d写入项目表中的专用列。

    方法选择 - >只要行数很少就行得很好 - >使用不断增长的日志和极高的CPU负载杀死我的服务器

    -- Select with CTE
    With G1 (P) as 
    (
        select PARENT  
        from parent_child
        where < ... condition> 
    ), G2 (C) as 
    (
        select CHILD 
        from parent_child
        where  < ... condition>
    )
    update Item_Master 
    set Item_Assembly_Level = '1' 
    where Item_Number in (select * from G1)  
      and Item_Number not in  (select * from G2) ;
    

2 个答案:

答案 0 :(得分:1)

你可以测试一下。

UPDATE I SET Item_Assembly_Level = 
            CASE 
                WHEN P.PARENT  IS NOT NULL AND C.CHILD  IS NULL THEN 1      --a) item is at least one time in Parent and NOT in Child
                WHEN P.PARENT  IS NOT NULL AND C.CHILD  IS NOT NULL THEN 2  --b) item is in Parent AND Child
                WHEN P.PARENT  IS NULL AND C.CHILD  IS NOT NULL THEN 3      --c) item is in Child AND NOT in Parent
                ELSE 4                                                  --d) is neither (ok - the rest...)
            END
FROM Item_Master I
    LEFT JOIN parent_child P ON I.Item_Number = P.PARENT 
    LEFT JOIN parent_child C ON I.Item_Number = C.CHILD 

答案 1 :(得分:0)

With G1 (P)
as (
select DISTINCT PARENT from parent_child
where < ... condition> 

EXCEPT

select DISTINCT CHILD from parent_child
where  < ... condition>
)
update Item_Master set Item_Assembly_Level = '1' where 
Item_Number in (select P from G1)
;