SQL SELECT:将PK与元组匹配,并从该元组的值中选择与该元组具有相同值的其他元组?

时间:2010-07-30 14:12:16

标签: sql select

我被困在家庭作业..

我如何从此表中检查cID,sID ='03'正在采取什么?然后,检查具有与sID ='03'相同的cID的其他sID并选择它?

sID    cID      year     grades
--------------------------------
01    L21D   1997   4
01    L24D   1998   2
01    L32D   1998   3
02    L21D   1998   3
02    L32D   1998   4
03    L32D   1998   

这是我想要选择的:

sID   cID 
-------------
01   L32D 
02   L32D 
03   L32D 

我尝试过不同的组合,但都没有给出我想要的东西。也许我现在太累了。

例如我试过这个:

 

SELECT sID FROM studentcourse WHERE sID = ( SELECT cID FROM studentcourse WHERE sID = '03' )

BR,Jay

4 个答案:

答案 0 :(得分:3)

sID ='03'的类正在采取:

Select cID from StudentsInClasses where sID = '03'

某些时候与sID ='03'(包括sID ='03')同一课程的学生:

Select 
    sID
From
    StudentsInClasses
Where
    cID in (Select cID from StudentsInClasses where sID = '03')

答案 1 :(得分:0)

这可以获得sID为'03'的cID:

select cID from table where sID = '03'

获取具有相同cID的其他sID的一种方法是将上述查询放入子查询中:

select * from table
where cID in (
    select cID from table where sID = '03'
)

答案 2 :(得分:0)

 SELECT cId, SId
 from table
 WHERE (cId, SID) IN (Select CId, SId from Table
                 WHERE sId = '03')

结果将是:

01 L32D
02 L32D
03 L32D

答案 3 :(得分:0)

使用:

SELECT t.cid, 
            t.sid
  FROM TABLE t
  JOIN TABLE x ON x.cid = t.cid
                    AND x.sid = '03'

它更具可读性:IN:

SELECT t.cid,
            t.sid
  FROM TABLE t
 WHERE t.cid IN (SELECT x.cid
                          FROM TABLE x
                         WHERE x.sid = '03')

使用EXISTS:

SELECT t.cid,
            t.sid
    FROM TABLE t
WHERE EXISTS(SELECT NULL
                        FROM TABLE x
                      WHERE x.cid = t.cid
                          AND x.sid = '03')