首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不同SQL查询效率

不同SQL查询效率
EN

Stack Overflow用户
提问于 2017-02-13 09:02:25
回答 2查看 36关注 0票数 0

项目中有一些与几个表相关的业务需求。在这些情况下,以下两个查询选项有利于性能优化。我该如何选择?首先:过滤笛卡尔产品:

代码语言:javascript
复制
select table1.a ,table2.b from table1 ,table2 where table1.id=table2.id 

第二:左外连接模式或右外连接模式。

代码语言:javascript
复制
 select table1.a ,table2.b from table1 left join table2 on table1.id=table2.id 

请告诉我。非常感谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-02-13 09:32:42

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

如果您想比较两种不同查询的性能,最简单的方法是运行这两种查询,并比较它们所用的时间,尽管通过比较查询计划来检查它们是否在做不同的事情( mysql中的EXPLAIN query text here将给出查询的计划)。

请注意,在编程中说“我知道它们给出了不同的结果,但我希望得到更快的结果”从来都不是一个明智的说法。你应该始终准确地知道你想要的结果。

也就是说。

代码语言:javascript
复制
select table1.a ,table2.b from table1 ,table2 where table1.id=table2.id

有同样的含义

代码语言:javascript
复制
select table1.a ,table2.b from table1 join table2 on table1.id=table2.id

代码语言:javascript
复制
select table1.a ,table2.b from table1 left join table2 on table1.id=table2.id

有同样的含义

代码语言:javascript
复制
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)

以及您没有使用的联接表单:

代码语言:javascript
复制
select table1.a ,table2.b from table1 right join table2 on table1.id=table2.id

有同样的含义

代码语言:javascript
复制
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)

代码语言:javascript
复制
select table1.a ,table2.b from table1 full join table2 on table1.id=table2.id

有同样的含义

代码语言:javascript
复制
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)
票数 0
EN

Stack Overflow用户

发布于 2017-02-13 09:13:01

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

在我的openion first查询中,运行时复杂度为O( n),在worsecase运行时复杂度为O(log ),其次是切换情况。

票数 -2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42200194

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档