简体   繁体   English

与postgresql的性能比较:left join vs union all

[英]Performance comparison with postgresql : left join vs union all

I want to know what is the best and the fastest solution between a "left outer join" and an "union all". 我想知道“左外连接”和“全部连接”之间最好和最快的解决方案是什么。 The database is a PostgreSQL. 该数据库是PostgreSQL。

Query with an UNION ALL : 使用UNION ALL查询:

SELECT * FROM element, user WHERE elm_usr_id = usr_id
UNION ALL
SELECT * FROM element WHERE elm_usr_id ISNULL;

Query with a LEFT OUTER JOIN : 使用LEFT OUTER JOIN进行查询:

SELECT * FROM element LEFT OUTER JOIN user ON elm_usr_id = usr_id;

I would suggest LEFT OUTER JOIN over union all in this particular scenario, 在这个特殊情况下,我建议LEFT OUTER JOIN over union all,

as in union all you have to read the tables twice, whereas in LEFT OUTER JOIN only once 因为在union中你必须两次读表,而在LEFT OUTER JOIN中只读一次

Probably the LEFT JOIN, but you can see the query plan by running EXPLAIN ANALYSE SELECT... . 可能是LEFT JOIN,但你可以通过运行EXPLAIN ANALYSE SELECT...来查看查询计划EXPLAIN ANALYSE SELECT... The UNION ALL form might be clearer if you were modifying columns based on the null-ness of elm_usr_id but you could always use CASE to do column modifications with a LEFT JOIN. 如果您基于elm_usr_id的null-ress修改列,则UNION ALL表单可能更清晰,但您始终可以使用CASE通过LEFT JOIN进行列修改。

Your two queries may not produce the same result. 您的两个查询可能不会产生相同的结果。

Your query with UNION ALL returns rows that matches plus rows that not matches because of a null value in elm_usr_id . 由于elm_usr_id中的空值,使用UNION ALL的查询将返回与不匹配的行匹配的行。

While the query with LEFT JOIN (same as LEFT OUTER JOIN) returns rows that matches plus rows that not matches because of any not corresponding value. 使用LEFT JOIN的查询(与LEFT OUTER JOIN相同)返回匹配的行以及由于任何不对应的值而不匹配的行。

Regarding to this, the query with LEFT JOIN is more secure if you expect to see all rows. 对此,如果您希望看到所有行,则使用LEFT JOIN的查询会更安全。

Back to your original question, the query with LEFT JOIN is the best on for taking advantage of indexes. 回到原来的问题,使用LEFT JOIN的查询是利用索引的最佳选择。 For example, if you'd like to have a sorted result, then the UNION query will be far slowest. 例如,如果您想要排序结果,那么UNION查询将是最慢的。 Or if your query is a subquery in a main query, then the UNION will prevent any possible exploitation of table [element] indexes. 或者,如果您的查询是主查询中的子查询,则UNION将阻止对表[element]索引的任何可能利用。 So it will be slow to perform a JOIN or WHERE of such a subquery. 因此,执行这样一个子查询的JOIN或WHERE会很慢。

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

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