select user不包含其他表sql查询中的记录

时间:2014-01-31 08:16:59

标签: sql record

我有三张桌子:sarcuser,sarcusercommittee,sarcallcourse。我需要构建一个查询,使所有没有委员会的用户(他们在sarcusercommittee中没有记录)。这是我目前的查询:

SELECT        u.firstname + ' ' + u.lastname AS name, u.dateofbirth, u.gender, LEFT(u.note, 200) AS note, c.name AS coursename
FROM            sarcuser AS u INNER JOIN
                         sarcusercommittee AS uc ON u.id = uc.user_id INNER JOIN
                         sarcallcourse AS c ON c.id = u.courseid
WHERE        ((SELECT        COUNT(id) AS Expr1
                            FROM            sarcusercommittee
                            WHERE        (user_id = u.id)) = 0)
ORDER BY name DESC

我想问题出在(ON condistion)但是没有得到它...任何帮助? 注意:我使用visual studio 2010

1 个答案:

答案 0 :(得分:0)

SELECT          u.firstname + ' ' + u.lastname AS name, u.dateofbirth, u.gender, LEFT(u.note, 200) AS note, c.name AS coursename
FROM            sarcuser AS u 
INNER JOIN      sarcallcourse AS c 
ON              c.id = u.courseid
WHERE           u.id NOT IN (
    SELECT      uc.user_id
    FROM        sarcusercommittee AS uc
)
ORDER BY name DESC

首先,如果你不想要它的行,你不应该内联到sarcusercommittee。 Seconly我会使用sarcusercommittee过滤给NOT IN以内的用户。