不同SQL查询效率

Different SQL query efficiency

项目中有一些业务需求涉及到几个表。在这些情况下,以下两个查询选项有利于性能优化。我该如何选择? First:Filter 笛卡尔积:

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 

请告诉我。非常感谢。

第二次查询更快。它没有嵌套条件。 SQL 引擎将连接视为单个 table 或视图。

在我的 openion 中,第一个查询作为 "For loop" 所以 运行 时间复杂度是 O(n),seconf 查询在更坏的情况下作为 Switch Case 运行时间复杂度是 O (登录 n)。

如果您以给出相同结果的形式编写它们,则期望查询分析器为您提供相同*的查询计划。也就是说 使用 JOIN 而不是 ,,因为 , 不太清楚,并且已经被弃用了几十年

如果您想比较两个不同查询的性能,最简单的方法是 运行 两者并比较它们花费的时间,尽管通过比较查询计划检查它们是否在做不同的事情 (EXPLAIN query text here in mysql 会给你查询的计划)

请注意,在编程中说 "I know they give different results, but I want the faster one" 从来都不是明智之举。您应该始终确切地知道您想要什么结果。

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)