对于新手sql问题很抱歉,但这不是同一回事:
select a.productid, sum(b.qty)
from table1 a
inner join table2 b on b.productid = a.productid
group by a.productid
;
select a.productid
,(select sum(b.qty) from table2 b where b.productid = a.productid)
from table1 a
group by a.productid
;
为什么有人会在选择中使用上面的查询,这是要忘记使用的一些老派东西,还是我应该考虑将其用于将来可能出现的一些问题?
答案 0 :(得分:2)
不,它们实际上不是一回事。有多个差异,但最明显的是 ERROR Failed to compile with 1 errors 22:51:02
error in ./src/components/Chart.vue
Syntax Error: this is a reserved word (57:12)
55 | }
56 | },
> 57 | mounted: {this.init()},
| ^
58 | methods: {
59 | init () {
60 | this.chart = this.$echarts.init(document.getElementById(this.id))
@ ./src/components/Chart.vue 4:0-105 5:0-118
@ ./src/router/index.js
@ ./src/main.js
@ multi (webpack)-dev-server/client?http://localhost:8080 webpack/hot/dev-server ./src/main.js
将过滤掉所有不匹配的行。相关的子查询将返回第一个表中的所有行。
还有其他区别。如果第一张表中有重复的join
,则sum()
将不相同。执行计划将有所不同(因为结果集不同)。在某些情况下,相关子查询会更快。
通常,在某些情况下,相关子查询是表达逻辑的最简单方法。而且,如上所述,它还可以在某些情况下制定最快的执行计划。
答案 1 :(得分:1)
第一个查询:
select a.productid, sum(b.qty)
from table1 a
inner join table2 b on b.productid = a.productid
group by a.productid
如果table2中没有相应的值,则不会返回行。
第二个查询就像LEFT JOIN
:
select a.productid
,(select sum(b.qty) from table2 b where b.productid = a.productid)
from table1 a
group by a.productid
<=>
select a.productid, sum(b.qty)
from table1 a
left join table2 b on b.productid = a.productid
group by a.productid
答案 2 :(得分:0)
请牢记性能...内部联接比子选择要快得多。子选择遍历所有匹配结果,因此复杂度为N x M ...导致性能不佳。在大多数情况下,联接的性能更好。