在带有SUM和group by的子查询中引用父查询中的表

时间:2013-06-17 09:26:42

标签: mysql sql

我的查询看起来像这样:

SELECT tablea.field,
(
 SELECT sum(count) FROM
 (
      SELECT count(distinct(subtable.regdate)) as count
      FROM subtable
      where subtable.regid = tableb.regid
      GROUP BY subtable.userid

 ) as a

) as thesum
FROM tablea 
LEFT JOIN tableb on tableb.id = tablea.tableaid
GROUP BY tablea.field2

问题是在我的子查询中引用的表“tableb”是未知的,所以我得到错误:“'where子句'中的未知列'tableb.regid'”

我该如何解决这个问题?

thx!

1 个答案:

答案 0 :(得分:1)

您可以将子查询移动到from子句:

SELECT tablea.field, thesum
FROM tablea left join
     tableb
     on tableb.id = tablea.tableaid left join
     (select st.regid, sum(count) as thesum
      from (SELECT st.regid, st.userid, count(distinct(st.regdate)) as count
            FROM subtable st
            GROUP BY st.regid, st.userid
           ) st
      group by st.regid
     ) st
     on st.regid = tableb.regid
GROUP BY tablea.field2;

但是,您的原始查询应该有效。我怀疑名字中有一个拼写错误。或者tableb实际上是在子查询中(在这种情况下它将超出范围),或者它有一个别名,你正在使用基表名。