2016-11-16 47 views
0

架構:有限公司相關MySQL中嵌套查詢

Student (snum: integer, 
     sname: char(30), 
     major: char(25), 
     level: char(2), 
     age: integer) 

Faculty (fid: integer, 
     fname: char(30), 
     deptid: integer) 

Class (cname: char(40), 
     meets_at: char(20), 
     room: char(10), 
     fid: integer | fid REFS Faculty.fid) 

Enrolled (snum: integer, 
      cname: char(40) | snum REFS student.snum, 
      cname REFS class.name) 

問題:

P1。查找教職員的姓名,授課人數最多不超過 的部門。

P2。發現有招生比5

我嘗試更多的所有類的名字和他們的招生力量:

#P1: 
select distinct f.fname,max(distinct c.cname) 
from faculty f,class c 
where Exists (select c.fid,max(distinct c.cname) as myCount 
from class c where 
f.fid=c.fid); 

#P2: 
select distinct c.cname 
from class c 
where Exists (select c.cname 
from enrolled e where 
e.cname=c.cname and count(e.cname)>5); 

但是,這是給我的錯誤。請幫助我。

+0

它給你一個錯誤?它是否得到錯誤的答案或解析查詢時出現錯誤? – jackarms

+0

P1 ----輸出錯誤 P2 ----無效使用組功能的 –

+1

推廣使用顯式的'JOIN' sintaxis,阿龍貝特朗寫了一篇很好的文章[不良習慣踢:使用舊樣式的JOIN(HTTP ://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/08/bad-habits-to-kick-using-old-style-joins.aspx)。 –

回答

0

,Q#1:只是做一個group by

select f.fname, COUNT(distinct c.cname) 
from faculty f 
join class c 
    on f.fid = c.fid 
group by f.fname 
order by COUNT(distinct c.cname) DESC 
limit 1 

使用相關查詢:

Corraleted V1:

SELECT * 
FROM faculty f 
WHERE f.id = (SELECT c.fid 
       FROM class c 
       GROUP BY c.fid 
       ORDER BY COUNT(distinct c.cname) DESC 
       LIMIT 1) 

Corraleted V2:

SELECT * 
FROM (
     SELECT f.*, (SELECT COUNT(distinct c.cname) 
        FROM class c 
        WHERE c.fid = f.id) as total 
     FROM faculty f 
    ) T 
ORDER By Total DESC 
LIMIT 1 
+0

我知道那位先生!我想通過使用相關的嵌套查詢概念來執行此查詢。 –

+0

你沒有說:(再次檢查,但我不喜歡那個。 –

+0

對不起,我沒有之前說的,但我試圖聯合相關嵌套查詢。 –

0

對於P2,您可以使用連接完成此操作,並且不需要嵌套查詢。在WHERE子句中,僅在HAVING子句中不允許對集合函數執行條件。您還必須先將班級名稱分組。

SELECT C.name, count(*) as enrollment 
FROM Class C INNER JOIN Enrolled E 
    ON C.cname=E.cname 
GROUP BY C.name 
HAVING count(*) > 5; 

做一個聯合相關嵌套查詢,試試這個:

SELECT C.cname, count(*) as enrollment_count 
FROM Class C INNER JOIN Enrolled E 
    ON C.cname = E.cname 
WHERE EXISTS (SELECT * 
       FROM Enrolled E 
       WHERE E.cname = C.cname 
       GROUP BY E.cname 
       HAVING count(*) > 5) 
GROUP BY C.cname; 
+0

推廣使用顯式'JOIN' sintaxis,阿龍貝特朗寫了一篇很好的文章[不良習慣踢:使用舊式聯接(http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/08/bad-habits-to )有關使用它的老風格,joins.aspx -kick- –

+0

我知道這件事,但我想通過聯合相關嵌套查詢概念來做到這一點。我們怎樣才能做到這一點? –

+0

錯誤。未知列C. cname在where子句中。 –