2012-04-17 56 views
0

我的查詢是:(查找,要麼在115房間裏開會或者有五個以上的學生就讀的所有類的名稱。)我想寫在mysql的這個查詢,你會幫我

CREATE TABLE STUDENT (
    sid NUMERIC(6) NOT NULL, 
    sname VARCHAR(15), 
    major VARCHAR(20), 
    level VARCHAR(2), 
    sage NUMERIC(2) NOT NULL, 
    PRIMARY KEY (sid) 
    ); 
CREATE TABLE CLASS(
    cnum VARCHAR(6), 
    meets_at TIME, 
    room VARCHAR(6), 
    fid NUMERIC(6) , 
    PRIMARY KEY (cnum), 
    FOREIGN KEY (fid) 
    references FACULTY (fid)  
    ); 
CREATE TABLE ENROLLED ( 
    cnum VARCHAR(6), 
    sid NUMERIC(6) NOT NULL, 
    PRIMARY KEY (cnum,sid), 
    FOREIGN KEY (sid) 
     REFERENCES STUDENT (sid), 
     FOREIGN KEY (sid) 
     REFERENCES FACULTY (fid), 
     FOREIGN KEY (cnum) 
     REFERENCES CLASS (cnum)   
    ); 
    alter table ENROLLED 
    add foreign key (sid) 
    references STUDENT (sid); 
+3

您是否嘗試過自己嗎?你嘗試了什麼? – Jon 2012-04-17 07:13:22

+0

...你的作業? – 2012-04-17 07:14:58

回答

0
SELECT `sid`, `cid` 
FROM (`STUDENT` INNER JOIN `ENROLLED` ON `STUDENT`.`sid` = `ENROLLED`.`sid`) 
    INNER JOIN `CLASS` ON `ENROLLED`.`cnum` = `CLASS`.`cnum` 
GROUP BY `ENROLLED`.`cid` 
HAVING 
    `CLASS`.`room` = '115' OR 
    COUNT(DISTINCT `STUDENT`.`sid`) >= 5 
1

也許是這樣的:

SELECT 
    * 
FROM 
    CLASS 
WHERE 
    CLASS.room='115' 
    OR 
    (
     SELECT 
      COUNT(*) 
     FROM 
      ENROLLED 
      JOIN STUDENT 
       ON ENROLLED.sid=STUDENT.sid 
     WHERE 
      ENROLLED.cnum=CLASS.cnum 
    )>=5 
+0

非常感謝你.......它的工作 – 2012-04-17 07:20:59

+0

也許你可以接受答案呢?還記得投票你認爲是好的答案。這給了我們一個模糊的感覺:P – Arion 2012-04-17 07:28:16

+0

:P肯定...... – 2012-04-17 07:34:17