如何在mysql中重用子查询结果
我正在做这样的统计工作:
SUM |COND1 |COND2 |...
--------------------------
100 |80 | 70 |...
SUM 结果是从多个表计算得出的,而 COND 是其子集。
我写了一个这样的sql:
select tmp1.id,sum,cond1,cond2 from (
select id, count(*) as sum from table1
group by table1.id) tmp1
left join (
select id, count(*) as cond1 from table1
where condition1
group by table1.id) tmp2 on tmp1.id=tmp2.id
left join (
select id, count(*) as cond2 from table1
where condition2
group by table1.id) tmp3 on tmp1.id=tmp3.id
问题是这样效率很差,如果我能使用tmp1的结果会更好,但我不知道该怎么做。
更新:简化了sql, 在这种情况下,第一个子查询:
select id, count(*) as sum from table1
group by table1.id) tmp1
被简化了,真正的查询是一个相当复杂的查询, 我的意思是当我计算 cond1 和 cond2 时如何重用这个嵌套选择结果。
I'm doing a statistic job like this:
SUM |COND1 |COND2 |...
--------------------------
100 |80 | 70 |...
The SUM result is calculated from multiple tables, and the CONDs are subset of that.
I wrote a sql like this:
select tmp1.id,sum,cond1,cond2 from (
select id, count(*) as sum from table1
group by table1.id) tmp1
left join (
select id, count(*) as cond1 from table1
where condition1
group by table1.id) tmp2 on tmp1.id=tmp2.id
left join (
select id, count(*) as cond2 from table1
where condition2
group by table1.id) tmp3 on tmp1.id=tmp3.id
the problem is that this is very poor efficiency, it will be better if i could use the result of tmp1, but i don't know how to do that.
update: simplified the sql,
the first subquery in this case:
select id, count(*) as sum from table1
group by table1.id) tmp1
is simpified , the real one is a pretty complex query,
what i mean is how to reuse this nested select result when i calculate cond1 and cond2.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该尝试重写您的查询,以便仅在一次表扫描中完成所有操作。使用 IF 语句:
如果您想写出正确的查询,请发布您的表结构:)
You should try to rewrite your query to do it all in only one table scan. Use the IF statement:
Post your table structure if you want the correct query written out :)