如何在mysql中重用子查询结果

发布于 2024-09-04 22:36:22 字数 814 浏览 4 评论 0原文

我正在做这样的统计工作:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烟酉 2024-09-11 22:36:22

您应该尝试重写您的查询,以便仅在一次表扫描中完成所有操作。使用 IF 语句:

SELECT id, 
COUNT(*) AS sum, 
SUM( IF( condition1 , 1, 0 ) ) cond1, -- emulates a count where condition1
SUM( IF( condition2, 1, 0 ) ) cond2   -- same thing, for condition2
FROM table1
GROUP BY id

如果您想写出正确的查询,请发布您的表结构:)

You should try to rewrite your query to do it all in only one table scan. Use the IF statement:

SELECT id, 
COUNT(*) AS sum, 
SUM( IF( condition1 , 1, 0 ) ) cond1, -- emulates a count where condition1
SUM( IF( condition2, 1, 0 ) ) cond2   -- same thing, for condition2
FROM table1
GROUP BY id

Post your table structure if you want the correct query written out :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文