考虑要更新的列更新多个表位于“where”

时间:2016-01-24 12:17:38

标签: sql sql-update

有3个表 - 1个父母和2个孩子(孩子PK有父亲PK的FK) 我需要更新所有3个表中的一些列,其中一个'where'取决于更新列。因此,在一个事务中它将是3个更新语句,但第一个更新会更改列和“where”变为篡改(对于最后两个更新)。 有没有解决这个问题的常用方法?

例如,有表格

figure(id, name) -- parent table
shape(id, shape) -- shape.id reference to figure.id
color(id, color) -- color.id reference to figure.id

我想将红色矩形更新为绿色方块,这意味着:

UPDATE shape SET shape.shape = 'square' 
   WHERE shape.id = (SELECT id FROM shape
                        INNER JOIN color ON color.id = shape.id
                        WHERE shape.shape ='rectangle'
                              AND color.color = 'red');

UPDATE color SET color.color = 'green' 
   WHERE color.id = (SELECT id FROM shape
                        INNER JOIN color ON color.id = shape.id
                        WHERE shape.shape ='rectangle'
                              AND color.color = 'red');

但是在第一次更新之后,没有任何“红色矩形”,因为它们变成了“方形”

所以,问题是:我是否必须创建一个临时表来选择ID然后执行更新,还是有另一种常见方式?

1 个答案:

答案 0 :(得分:1)

这样的事情:

SELECT DISTINCT shape.id
INTO #tempIds
FROM shape
INNER JOIN color ON color.id = shape.id
WHERE shape.shape ='rectangle'
  AND color.color = 'red'
;

UPDATE shape SET shape.shape = 'square' 
WHERE shape.id IN (SELECT id FROM #tempIds)
;

UPDATE color SET color.color = 'green' 
WHERE color.id = (SELECT id FROM #tempIds)
;

也可能想在此周围抛出事务和错误处理。