2017-02-13 127 views
0

项目中存在与少数几个表相关的业务需求。在这些情况下,以下两个查询选项对性能优化是有利的。我应该如何选择? 第一:过滤笛卡尔乘积:不同的SQL查询效率

select table1.a ,table2.b from table1 ,table2 where table1.id=table2.id 

二:左外连接方式或右外连接方式

select table1.a ,table2.b from table1 left join table2 on table1.id=table2.id 

请告诉我。非常感谢你。

+0

我不明白的问题一样一样的。你能否详细说明一下? – 0xCAFEBABE

+0

这两者并不相同。 'LEFT JOIN'将返回没有匹配'table2'行的'table1'行,笛卡尔积不会返回这些行。 – Barmar

+0

@ 0xCAFEBABE使用上述两种方式查询出相同的数据,但我想知道在哪种情况下使用这种方式的性能会更好 – lpgad

回答

0

如果您将它们写入表单中,并且结果相同,则希望查询分析器为您提供相同的*查询计划。这就是说使用JOIN不,,因为,是那么清楚,并已经被废弃了几十年

如果要比较两个不同的查询的性能,最简单的方法是同时运行和比较能维持多久虽然通过比较查询计划(mysql中的EXPLAIN query text here将为您提供查询计划)来检查他们是否做了不同的事情,但请注意,说“我知道他们给出了不同的结果,但我想要更快的一个”在编程中从来不是一件明智的事情。你应该始终知道你想要的结果。

I.e.

select table1.a ,table2.b from table1 ,table2 where table1.id=table2.id 

的含义

select table1.a ,table2.b from table1 join table2 on table1.id=table2.id 

select table1.a ,table2.b from table1 left join table2 on table1.id=table2.id 

相同的含义

select table1.a ,table2.b from table1 ,table2 where table1.id=table2.id 
union 
select table1.a , null from table1 where table1.id not in (select table2.id from table2) 

和连接,你没有使用相同的形式:

select table1.a ,table2.b from table1 right join table2 on table1.id=table2.id 

的含义

select table1.a ,table2.b from table1 ,table2 where table1.id=table2.id 
union 
select null, table2.b from table2 where table2.id not in (select table1.id from table1) 

而且

select table1.a ,table2.b from table1 full join table2 on table1.id=table2.id 

的含义

select table1.a ,table2.b from table1 ,table2 where table1.id=table2.id 
union 
select table1.a , null from table1 where table1.id not in (select table2.id from table2) 
union 
select null, table2.b from table2 where table2.id not in (select table1.id from table1) 
-2

第二个查询速度更快。它没有嵌套条件。 SQL引擎将联接视为单个表或视图。

在我的openion中,第一个查询作为“For循环”工作,因此运行时复杂度为O(n),并且seconf查询在reduce case运行时的复杂度为O(log n)时作为Switch Case工作。

+0

在任何情况下,第二个比第一个好? – lpgad

+0

SQL执行查询计划步骤。 OP的两个查询将会有类似的计划(如果他从'left join'更改为'join',则相同) – Caleth