结合subselect

时间:2010-07-15 16:37:47

标签: mysql subquery

我必须将为mysql5编写的查询重写为mysql4.0,不支持sub select我有这样的查询:

select a,
       c,
       (select count(*) from A) as e 
          from (select b, sum(e) as a 
                  from B 
                 where h = "foo" 
              group by b) TABLEB,
       (select sum(d),
               count(*) as c 
          from C 
         where d = "bar") TABLEC

我尝试在一个请求中合并TABLEA和TABLE B,但sum()结果不正确(sum(e)值变为sum(e)乘以TABLEC的行数)

所有分组的值都成为实际值的倍数(取决于行数)。

是否可以将此查询转换为mysql 4.0的一个查询,还是必须将其拆分为3个查询?

1 个答案:

答案 0 :(得分:2)

为什么你要迁移到MySQL 4.0?它是古老的历史,缓慢,马车和不安全。如果您使用的是仍在运行MySQL 4.0的托管服务,请切换到其他托管服务。

但不管怎样,我认为没有理由将这些查询合并为一个,即使你使用的是MySQL 5.0。每个表的结果与其他表没有关系。

只需运行三个查询:

select b, sum(e) as esum from B where h = 'foo' group by b;

select sum(d) as dsum, count(*) as c from C where d = 'bar';

select count(*) as acount from A;

p.s。:在SQL中使用单引号作为字符串文字。