更新子查询的WHERE子句中的UNION

时间:2016-03-01 14:02:24

标签: mysql sql correlated-subquery

为什么UNION不应该在更新子查询的WHERE子句中使用?或者就此而言,甚至是正常的选择子查询?

这样的查询是否有更好的方法来消除UNION?

请注意,对于我的情况,UNION将产生相当少量的记录。

UPDATE mytable
set mytable.bla='xxx'
WHERE id IN (
    SELECT id
    FROM t1
    INNER JOIN t2 ON t2.t1_id=t1.id
    LEFT OUTER JOIN t3 ON t3.t1_id=t2.id
    WHERE t2.id IN (1,2,3) AND t3.id IS NULL
    UNION
    SELECT id FROM t4
    INNER JOIN t5 ON t5.id=t4.t5_id
    LEFT OUTER JOIN t6 ON t6.t5_id=t5.id
    WHERE t5.parent_id IN (1,2,3) AND t6.id IS NULL
);

1 个答案:

答案 0 :(得分:1)

将其切换为联接: -

UPDATE mytable 
INNER JOIN
(
    SELECT id
    FROM t1
    INNER JOIN t2 ON t2.t1_id=t1.id
    LEFT OUTER JOIN t3 ON t3.t1_id=t2.id
    WHERE t2.id IN (1,2,3) 
    AND t3.id IS NULL
    UNION
    SELECT id 
    FROM t4
    INNER JOIN t5 ON t5.id=t4.t5_id
    LEFT OUTER JOIN t6 ON t6.t5_id=t5.id
    WHERE t5.parent_id IN (1,2,3) 
    AND t6.id IS NULL
) sub0
ON mytable.id = sub0.id
SET mytable.bla='xxx'