仅显示与临时表中的最大值相等的实例

时间:2017-03-07 20:11:16

标签: mysql sql

我尝试创建一个只包含sname的新表格,该表格等于num_courses的最大数量,这是临时表{{1}中的一列}。

n

是否可以只显示与临时表中找到的最大值相等的实例? (参考最后一行的第二个SELECT s.sname, n.num_courses FROM (SELECT e.sid, COUNT(distinct e.cno) as num_courses FROM enroll e GROUP BY e.sid) n, student s WHERE s.sid = n.sid AND n.num_courses = (SELECT MAX(n.num_course) from n) x; 子句)

这是错误:

WHERE

它说错误在第1行,但是当我删除最后一行的最后一个句子时,没有错误。

3 个答案:

答案 0 :(得分:2)

您无法像这样重用子查询。您需要在where子句中再次编写查询。

我认为你打算这样做:

select s.sname,
    n.num_courses
from (
    select e.sid,
        COUNT(distinct e.cno) as num_courses
    from enroll e
    group by e.sid
    ) n,
    student s
where s.sid = n.sid
    and n.num_courses = (
        select MAX(n.num_course)
        from (
            select COUNT(distinct e.cno) as num_courses
            from enroll e
            group by e.sid
            ) t
        );

答案 1 :(得分:2)

您不需要x tablename,也不能使用n表别名,但需要所有代码

  SELECT s.sname, n.num_courses
  FROM (SELECT e.sid, COUNT(distinct e.cno) as num_courses
        FROM enroll e
        GROUP BY e.sid) n 
  INNER JOIN  student s ON s.sid = n.sid AND  (SELECT MAX(n.num_course) from 
  ( SELECT e.sid, COUNT(distinct e.cno) as num_courses
        FROM enroll e
        GROUP BY e.sid) n )

答案 2 :(得分:1)

您不需要year(letter_sent_date)条件下的别名,也可以尝试使用WHERE,因为IN可能会返回多个结果,例如

MAX()