简体   繁体   中英

LEFT OUTER JOIN with OR versus UNION

Are there significant performance considerations between using UNION versus LEFT OUTER JOIN with OR in the WHERE clause?

What is the difference between these two queries?

Is it often better to use LEFT OUTER JOINs instead of a UNION?

My reason for asking is I actually need to do an INSERT, and can't use a UNION even if I wanted to.

SELECT t.foo
FROM t
INNER JOIN t1 t1.t_id=t.id
WHERE t1.id IN (1,2,3)
UNION
SELECT t.foo
FROM t
INNER JOIN t2 t2.t_id=t.id
INNER JOIN t2a ON t2a.t2_id=t2.id
WHERE t2a.id IN (1,2,3)
UNION
SELECT t.foo
FROM t
INNER JOIN t3 t3.t_id=t.id
INNER JOIN t3a ON t3a.t3_id=t3.id
WHERE t3a.id IN (1,2,3);

SELECT DISTINCT t.foo
FROM t
LEFT OUTER JOIN t1 t1.t_id=t.id
LEFT OUTER JOIN t2 t2.t_id=t.id
LEFT OUTER JOIN t2a ON t2a.t2_id=t2.id
LEFT OUTER JOIN t3 t3.t_id=t.id
LEFT OUTER JOIN t3a ON t3a.t3_id=t3.id
WHERE t1.id IN (1,2,3) OR t2a.id IN (1,2,3) OR t3a.id IN (1,2,3);

UPDATE t
LEFT OUTER JOIN t1 t1.t_id=t.id
LEFT OUTER JOIN t2 t2.t_id=t.id
LEFT OUTER JOIN t2a ON t2a.t2_id=t2.id
LEFT OUTER JOIN t3 t3.t_id=t.id
LEFT OUTER JOIN t3a ON t3a.t3_id=t3.id
SET t.foo="bar"
WHERE t1.id IN (1,2,3) OR t2a.id IN (1,2,3) OR t3a.id IN (1,2,3);

As with many performance questions, you should test the results on your data and your systems. The union and left join s are doing very different things -- and which is better probably depends on features of your data, available indexes, and other considerations.

However, you can use the union method in update . You just need a subquery:

update t join
       (select t.id, t1.foo . . .
        union . . . 
        select t.id, t2.foo
       ) tt
       on t.id = tt.id
    set t.foo = 'foo'
    where . . .;

You might also find it more efficient to use the union approach but to break the update into multiple separate update statements.

You can use UNION in inserts.

INSERT INTO `table`
SELECT * FROM   
(
    SELECT '1'
    UNION
    SELECT '2'
) x

Same goes for updates:

UPDATE `table1` t1
JOIN (
    SELECT '1' as col1
    UNION
    SELECT '2'
) x ON x.col1 = t1.colX  
SET t1.whateverColumn = "someValue"

As for performance, it's mainly down to indexes. Both can be fast, both can be slow. If you're indexing them correctly, you shouldn't see big differences between the two.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM