2017-03-07 24 views
1

我试图创建一个新表,其中只有sname的最大值等于num_courses这是临时表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条款的最后一行)

这是错误:

ERROR 1064 (42000) at line 1 in file: 'q7.sql': You have an error in your 
SQL syntax; check the manual that corresponds to your MySQL server version 
for the right syntax to use near 'x' at line 5 

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

回答

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

你并不需要一个别名WHERE条件,并尝试使用IN因为代替MAX()可能返回多个结果像

n.num_courses IN (SELECT MAX(n.num_course) from n); 
+0

没有分组by子句。所以max将**从不**在这里返回多行。 – GurV

+1

这似乎也不起作用。仍然给我一个错误。 –

2

你不需要x表名,你不能使用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) 
+0

正是我所回答的。 – GurV

+0

我使用更合适的..加入格式..但问题是一样 – scaisEdge

+0

有我使用显式连接upvote。 :-) – GurV

相关问题