在WHERE子句中使用SELECT查询

时间:2013-03-01 08:11:15

标签: sql where

我想列出一个表中的行,这些行与需要比较两个表中的记录列表的where子句有关

SELECT DISTINCT (CONA.DOCUMENTID), CONA.CONTENTID 
FROM TABLEA AS CONA 
INNER JOIN TABLEB AS CTAGA ON CTAGA.CONTENTID = CONA.CONTENTID
WHERE CONA.DOCUMENTID LIKE 'PM%' 
AND (
  SELECT TAGID 
  FROM  TABLEB 
  WHERE CTAGA.CONTENTID = CONA.CONTENTID
) IN (SELECT TAGID FROM TABLEC)

在上面的SELECT TAGID FROM TABLEB WHERE CTAGA.CONTENTID = CONA.CONTENTID中会有

ABC,DEF,GHI,JKL,MNO

SELECT TAGID FROM TABLEC将有abc,def,ghi,jkl,mno,pqr,stu

是否可以检查列表A中的所有记录是否在列表B

使用上面的I另外表中的多个值

2 个答案:

答案 0 :(得分:0)

试试这个

 SELECT DISTINCT (CONA.DOCUMENTID),TAGID FROM TABLEB As CTAGA
 Join TABLEC As CONA  On CTAGA.CONTENTID = CONA.CONTENTID
 Where CTGA.TAGID in (SELECT TAGID FROM TABLEC)
 AND CONA.DOCUMENTID LIKE 'PM%'

答案 1 :(得分:0)

尝试此查询

SELECT DISTINCT (CONA.DOCUMENTID), CONA.CONTENTID 
FROM TABLEA AS CONA INNER JOIN TABLEB AS CTAGA ON CTAGA.CONTENTID = CONA.CONTENTID 
                      AND CTAGA.TAGID IN (SELECT TAGID FROM TABLEC)                    
WHERE CONA.DOCUMENTID LIKE 'PM%'

OR

SELECT DISTINCT (CONA.DOCUMENTID), CONA.CONTENTID 
FROM TABLEA AS CONA INNER JOIN TABLEB AS CTAGA ON CTAGA.CONTENTID = CONA.CONTENTID                                          
WHERE CONA.DOCUMENTID LIKE 'PM%' AND EXISTS (
                                             SELECT 1 
                                             FROM TABLEC
                                             WHERE CTAGA.TAGID = TABLEC.TAGID
                                             )