Search code examples
mysqlsqlcorrelated-subquery

UNION in WHERE clause of update subquery


Are there any reasons why UNIONs shouldn't be used in the WHERE clause of update subqueries? Or for that matter, even normal select subqueries?

Is there a better way such a query to eliminate the UNION?

Note that for my case, the UNION will result in a fairly small number of records.

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
);

Solution

  • Switching it to a join:-

    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'