MSSql查询问题

时间:2016-02-15 12:29:46

标签: sql-server

我有三张桌子

-Projects(ProjectId[PK], Status ...)
-UserProjects(UserProectId[PK], ProectId[FK], UserId[FK], ...)
-Users(UserId[PK], ...)

我想选择状态为1的项目,项目必须是不参与用户的项目。

这是我尝试过的:

Select UP.ProjectId from UserProjects UP
Join Projects P on UP.ProjectId = P.ProjectId
Where P.Status = 1 AND UP.UserId != 1

我想要的结果应该只是16.它也给了我17,因为用户1和用户3都在项目17中。

任何人都知道如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

您可以使用HAVING子句进行分组:

SELECT UP.ProjectId 
FROM UserProjects UP
INNER JOIN Projects P ON UP.ProjectId = P.ProjectId
WHERE P.Status = 1 
GROUP BY  UP.ProjectId 
HAVING COUNT(CASE WHEN UP.UserId = 1 THEN 1 END) = 0

HAVING子句使用UserId = 1过滤掉与用户相关的项目。

或者,您可以使用NOT EXISTS

SELECT ProjectId
FROM Projects AS P
WHERE Status = 1 AND 
      NOT EXISTS(SELECT 1
                 FROM UserProjects AS UP
                 WHERE UP.ProjectId = P.ProjectId AND UP.UserId = 1)