简体   繁体   English

左外连接与OR或UNION

[英]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? 在WHERE子句中将UNION与LEFT OUTER JOIN与OR结合使用时,是否需要考虑重要的性能?

What is the difference between these two queries? 这两个查询有什么区别?

Is it often better to use LEFT OUTER JOINs instead of a UNION? 使用左外部联接代替UNION通常会更好吗?

My reason for asking is I actually need to do an INSERT, and can't use a UNION even if I wanted to. 我问的原因是我实际上需要执行INSERT,即使我想也不能使用UNION。

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. unionleft join的工作截然不同-最好取决于数据的功能,可用索引和其他考虑因素。

However, you can use the union method in update . 但是,您可以update使用union方法。 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. 您可能还会发现使用union方法更有效,但可以将更新分为多个单独的update语句。

You can use UNION in inserts. 可以在插入中使用UNION

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. 如果正确地为它们建立索引,那么您应该不会在两者之间看到很大的差异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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