从列的表中选择所有内容

时间:2013-08-31 18:15:06

标签: mysql mysql-5.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))); 

并收到以下错误:

  

错误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  
即使在我的数据库中有一个教职员去所有房间,也得到了“空集”。

2 个答案:

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

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