得到错误:表不存在

时间:2014-01-08 11:20:59

标签: mysql sql

我有3列:

  1. 大学( cname ,州,招生)
  2. 学生( sid ,sname,gpa,sizehs)
  3. 申请( sid ,cname,major,decision)

我尝试了这个查询:

select j.major , max(j.gpa)
from (select s.* , a.cname , a.major, a.decision 
        from student s join apply a on s.sid = a.sid and decision = 'y') j
group by major
这是有效的。但当我再添加一个feild来选择时,它就会破坏:

select major , sname , max(gpa) , (select avg(gpa) from j) as avg -- trouble
from (select s.* , a.cname , a.major, a.decision 
        from student s join apply a on s.sid = a.sid and decision = 'y') j
group by major
having max(gpa) < avg;

我收到错误消息:表j不存在。为什么会这样?
 如果 j 不存在,那么在第一个查询中,当我说j.gpa等时,它就可以了。

我的目标是找到Majors whose applicant's maximum GPA is below the average,我提出了一个有效的查询:

select major , sname , student.sid , gpa , 
    (select round(avg(gpa),5) as avg from student join apply 
        on student.sid = apply.sid and decision='Y') as avg
from student join apply on student.sid = apply.sid and decision='Y'
group by major
having max(gpa) < avg

但是在这里,我必须在selectfrom中输入连接部分。我希望有一些方法可以跳过两次输入连接部分,所以我想出了上面的(错误的)查询。

任何帮助都会很棒。

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT major, 
       sname, 
       Max(gpa), 
       Avg(gpa) AS avg_gpa 
FROM   (SELECT s.*, 
               a.cname, 
               a.major, 
               a.decision 
        FROM   student s 
               JOIN apply a 
                 ON s.sid = a.sid 
                    AND a.decision = 'y') j 
GROUP  BY major 
HAVING Max(gpa) < avg_gpa; 

这是因为j是select查询的别名,您在初始化之前在上面的select查询中使用它。首先,它将执行子查询,然后从那里选择列。而且这个表格找不到。

答案 1 :(得分:0)

试试这个:

SELECT major, 
       sname, 
       Max(gpa), 
       Avg(gpa) AS avgA 
FROM   (SELECT s.*, 
               a.cname, 
               a.major, 
               a.decision 
        FROM   student s 
               JOIN apply a 
                ON s.sid = a.sid 
                   AND decision = 'y') j 
GROUP  BY major 
HAVING Max(gpa) < avga;