2017-03-07 32 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