一个更简单的SQL查询

时间:2012-10-05 05:38:22

标签: sql oracle

我有以下表格

  • 学生(sid,sname,年龄)
  • 当然(cid,cname,duration)
  • 注册(sid,cid,date)

找到所有参加过sid = 1课程的sid。

select sid from enroll where cid in (select cid from enroll where sid=1) 
group by sid having count(*)=(select count(*) from enroll where sid=1) 
minus (select sid from student where sid=1);
  1. 第一次计数(*)是指什么?
  2. 是否有更简单的查询版本?

2 个答案:

答案 0 :(得分:0)

第一个COUNT(*)是指属于特定sid的行数。

重新格式化:

SELECT sid
  FROM enroll
 WHERE cid IN (SELECT cid FROM enroll WHERE sid=1) 
 GROUP by sid
HAVING COUNT(*) = (SELECT COUNT(*) FROM enroll WHERE sid=1) 
MINUS (SELECT sid FROM student WHERE sid=1);

你当然可以通过使用:

来避免使用MINUS
SELECT sid
  FROM enroll
 WHERE cid IN (SELECT cid FROM enroll WHERE sid=1)
   AND sid != 1
 GROUP by sid
HAVING COUNT(*) = (SELECT COUNT(*) FROM enroll WHERE sid=1) 

答案 1 :(得分:0)

试试这个

SELECT s.sid
FROM student s, enroll e
WHERE s.sid = e.sid
AND e.cid IN (SELECT cid FROM course WHERE sid=1)
AND s.sid <> 1