为什么这两个sql的结果不同

时间:2012-06-29 16:33:46

标签: sql db2

我尝试使用以下查询更新表中的列。在这种情况下,32000行将更新。

Update Table72D012 t2 set DEFINING_ARGUMENT_ID = 
(
SELECT   t3.ID
FROM     Table70t3 t3,
         Table70t1 t1,
         Table70t0 t0,         
         Table4 t4
WHERE    t2.Model_id = t4.ID
AND      t3.ID = t1.PARAM_VALUE_BPVA_ID
AND      t3.VALUE_BPAR_ID = t0.ID
AND      t0.KEY='SPECIAL_KEY'
AND      t1.LANGUAGE='en'
AND      t4.Model = t1.name

);

我想检查结果,并使用以下查询来获取相关ID的计数。我得到了结果26500 ..为什么结果(更新次数和选择结果的次数)彼此不同?
如何更正UPDATE查询?

仅选择

SELECT   t3.ID
FROM     Table70t3 t3,
         Table70t1 t1,
         Table70t0 t0,
         Table72D012 t2,
         Table4 t4
WHERE    t2.Model_id = t4.ID
AND      t3.ID = t1.PARAM_VALUE_BPVA_ID
AND      t3.VALUE_BPAR_ID = t0.ID
AND      t0.KEY='SPECIAL_KEY'
AND      t1.LANGUAGE='en'
AND      t4.Model = t1.name

1 个答案:

答案 0 :(得分:3)

首先,您需要学习正确的连接语法。在WHERE子句中进行连接是个坏主意。

原因很简单。第一个查询是更新表中的非常行,因为您没有WHERE子句或其他条件。

第二个查询返回与查询匹配的所有行。在更新版本中,这些行将获得NULL值。

这是一个很好的语法,由MS SQL支持,但不是由DB2支持:

Update Table72D012 t2
    set DEFINING_ARGUMENT_ID = t3.ID
    from (SELECT t4.id as t4_id, t3.ID
          FROM Table70t3 t3 join 
               Table70t1 t1
               on t3.ID = t1.PARAM_VALUE_BPVA_ID join
               Table70t0 t0
               on t3.VALUE_BPAR_ID = t0.ID join
               Table4 t4 
               on t4.Model = t1.name
          WHERE t0.KEY='SPECIAL_KEY' AND t1.LANGUAGE='en'
          ) t
    WHERE t2.Model_id = t4_ID

我认为DB2不允许在UPDATE中使用FROM子句,所以你需要这样的东西:

Update Table72D012 t2
    set DEFINING_ARGUMENT_ID = 
         (SELECT t3.ID
          FROM Table70t3 t3 join 
               Table70t1 t1
               on t3.ID = t1.PARAM_VALUE_BPVA_ID join
               Table70t0 t0
               on t3.VALUE_BPAR_ID = t0.ID join
               Table4 t4 
               on t4.Model = t1.name
          WHERE t0.KEY='SPECIAL_KEY' AND t1.LANGUAGE='en' and t2.Model_id = t4.ID
          ) 
    WHERE exists              
         (SELECT t3.ID
          FROM Table70t3 t3 join 
               Table70t1 t1
               on t3.ID = t1.PARAM_VALUE_BPVA_ID join
               Table70t0 t0
               on t3.VALUE_BPAR_ID = t0.ID join
               Table4 t4 
               on t4.Model = t1.name
          WHERE t0.KEY='SPECIAL_KEY' AND t1.LANGUAGE='en' and t2.Model_id = t4.ID
          )