选择另一个表中没有对应行的表行

时间:2013-12-31 16:04:35

标签: sql select visual-web-developer-2010

当ReqID介于5和8之间并且tblSomeTable中没有相应的行时,我正试图从tblReqInfo获取行

SELECT        *
FROM            tblReqInfo
WHERE         (RI_ReqID BETWEEN 5 AND 8)
             AND 
                          CASE
                                WHEN NOT EXISTS   
                                      (SELECT        CC_ReqID
                                        FROM            tblSomeTable
                                        WHERE        (CC_UserID = @CC_UserID) )
                                 THEN  1
                                 ELSE  RI_ReqID NOT IN (SELECT        CC_ReqID
                                        FROM            tblSomeTable
                                        WHERE        (CC_UserID = @CC_UserID) )
                           END 
ORDER BY RI_ReqID

不幸的是,查询配置向导甚至无法解析此问题。任何人都可以看出哪些查询对我有用吗?

2 个答案:

答案 0 :(得分:1)

在SQL Server中尝试:

SELECT        *
FROM            tblReqInfo
WHERE         (RI_ReqID BETWEEN 5 AND 8)
AND RI_ReqID NOT IN 
                 (SELECT        CC_ReqID
                  FROM            tblSomeTable
                  WHERE        CC_UserID = @CC_UserID)

答案 1 :(得分:1)

此问题的标准解决方案是执行从目标表到引用表的外部联接,然后获取指示对象中没有匹配项的行:

SELECT target.*, referent.id
FROM   target   LEFT OUTER JOIN
       referent ON (target.id = referent.id)
WHERE  target.id BETWEEN 5 and 8
  AND  referent.id IS null
ORDER  BY target.id