【问题标题】:how to reuse subquery result in mysql如何在mysql中重用子查询结果
【发布时间】:2011-03-02 05:07:43
【问题描述】:

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

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 时如何重用这个嵌套的选择结果。

【问题讨论】:

  • 您发布的内容过于抽象 - 请提供更多详细信息。遗憾的是,MySQL 不支持 WITH 子句...

标签: mysql select performance nested subquery


【解决方案1】:

您应该尝试重写查询以仅在一次表扫描中完成所有操作。使用 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

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

【讨论】:

  • 太棒了!!这就是我想要的!!
  • 如果没有 where 子句,这会进行全表扫描。如果表很大,您可能会更快地将条件添加到“where condition1 OR condition2 OR ...”,或者只使用 UNION 语句。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多