Mysql Aggregate操作子查询

时间:2014-10-23 02:19:02

标签: mysql subquery

$query = "Select first-second as ss from 
          (
           SELECT sum(mysum) from 
              (
                 SELECT pow(sum(ans),2)/count(staff_id) as mysum 
                 from answer 
                 group by staff_id
              )as EEx2
          ) as first from
          (
                  select pow(sum(ans),2)/count(ans) as sumofans
                  from answer 
          ) as second";

我得到错误:您的SQL语法有错误;查看与您的MySQL服务器版本对应的手册,以便在'from(选择pow(sum(ans),2)/ count(ans)附近使用正确的语法作为答案中的sumofans

我坚持了几天。任何人都可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

这是您的查询:

Select first-second as ss from 
(
   SELECT sum(mysum) from 
   (
     SELECT pow(sum(ans),2)/count(staff_id) as mysum 
     from answer 
     group by staff_id
   ) as EEx2
) as first from 
(
  select pow(sum(ans),2)/count(ans) as sumofans
  from answer 
) as second

这在语法上是不正确的。单个选择只有一个from子句。此外,您不在第一个查询中命名列。我想你想要:

Select (first.mysum - second.sumofans) as ss from 
(
  SELECT sum(mysum) as mysum from 
  (
   SELECT pow(sum(ans),2)/count(staff_id) as mysum 
   from answer 
   group by staff_id
   ) as EEx2
 ) as first cross join
 (
   select pow(sum(ans),2)/count(ans) as sumofans
   from answer 
 ) as second

答案 1 :(得分:0)

$query = "Select first-second as ss from 
      (
       SELECT sum(mysum) from 
          (
             SELECT pow(sum(ans),2)/count(staff_id) as mysum 
             from answer 
             group by staff_id
          )as EEx2
      ) as first // use inner join , join etc here not from.. 
      (
              select pow(sum(ans),2)/count(ans) as sumofans
              from answer 
      ) as second";

这里的问题是你在单一选择中使用两次键。