我想在mysql中写这个查询,请你帮帮我

时间:2012-04-17 07:11:17

标签: mysql

我的查询是:(查找在115室会议或有五个或更多学生注册的所有课程的名称。)

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);

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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