0

在我的 mysql 数据库中,我有以下表格:

FACULTY (fid int, fname varchar(25), deptid int, primary key(fid))  
CLASS (name varchar(4),meets_at varchar(9),room varchar(4), fid int,primary key (name), foreign key (fid) references faculty (fid))  

我想选择去所有​​房间的学院的名字。我尝试使用以下内容:

SELECT DISTINCT F.FNAME   
FROM FACULTY F  
WHERE NOT EXISTS (( SELECT *  
FROM CLASS C  
EXCEPT  
(SELECT C1.ROOM  
FROM CLASS C1  
   WHERE C1.FID=F.FID))); 

并得到以下错误:

ERROR 1064 (42000):您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以获取在 'EXCEPT 附近使用的正确语法

还尝试过:

SELECT DISTINCT F.FNAME   
FROM FACULTY F   
LEFT JOIN CLASS C ON C.FID = F.FID  
WHERE C.FID IS NULL  

并得到“空集”,即使在我的数据库中有一个教师去所有房间。

4

2 回答 2

1

当你except必须使用这两个表时compatible,试试这个:

SELECT DISTINCT F.FNAME   
FROM FACULTY F  
WHERE NOT EXISTS (
( SELECT ROOM  
FROM CLASS C)
EXCEPT  
(SELECT C1.ROOM  
FROM CLASS C1  
   WHERE C1.FID=F.FID)
); 

编辑

这个问题被标记到 sql server 所以我给出了答案,记住这一点,对于 mysql 使用这个:

SELECT FID, COUNT(*) FROM
(
    (SELECT DISTINCT f.fname, f.fid, c1.room 
    FROM faculty f
    JOIN class c1 
    ON f.fid = c1.fid) tb1 
JOIN
    (SELECT DISTINCT room AS room2 FROM class) tb2
ON tb1.room = tb2.room2
)
GROUP BY FID
HAVING COUNT(*) IN (SELECT COUNT(DISTINCT Room) FROM Class);

小提琴:http ://sqlfiddle.com/#!8/cff12/4

于 2013-08-31T18:35:13.123 回答
0

我的观点与您的问题有关。

SELECT T.fid FROM
  (SELECT f.fid FROM 
     faculty f LEFT JOIN class c ON f.fid = c.fid) T
  GROUP BY T.fid 
  HAVING(
    COUNT(T.fid) = (SELECT COUNT(DISTINCT room) FROM class))

SQL小提琴

于 2013-08-31T22:15:22.353 回答