不同的SQL查询效率
问题描述:
项目中存在与少数几个表相关的业务需求。在这些情况下,以下两个查询选项对性能优化是有利的。我应该如何选择? 第一:过滤笛卡尔乘积:不同的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
请告诉我。非常感谢你。
答
如果您将它们写入表单中,并且结果相同,则希望查询分析器为您提供相同的*查询计划。这就是说使用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)
我不明白的问题一样一样的。你能否详细说明一下? – 0xCAFEBABE
这两者并不相同。 'LEFT JOIN'将返回没有匹配'table2'行的'table1'行,笛卡尔积不会返回这些行。 – Barmar
@ 0xCAFEBABE使用上述两种方式查询出相同的数据,但我想知道在哪种情况下使用这种方式的性能会更好 – lpgad