SQL Server - 添加条件内连接

时间:2015-02-09 01:04:37

标签: sql sql-server inner-join

我是数据库开发的新手,我是一个存储过程,只有在满足条件时我才需要对表进行一些INNER JOIN。下面是我的复杂查询的较短版本。

IF (testFunction(@UserId)) = 0 
  select C.AwardId, C.ProgramName, Count(ClientId) as Intakes from Client C 
    where C.Id = @ClientId
    group by C.AwardId, C.ProgramName...
ELSE
  select C.AwardId, C.ProgramName, Count(ClientId) as Intakes from Client C
    INNER JOIN UserRoleEntity URE ON C.AwardId = URE.EntityId 
    INNER JOIN UserRole UR ON URE.UserRoleId = UR.Id AND UR.CDPUserId = @UserId
         where C.Id = @ClientId
         group by C.AwardId, C.ProgramName...
END

基本上,它在" IF"中都是相同的SELECT查询。和" ELSE"除了在不满足IF条件时我需要在2个表上进行内连接。而不是在" IF"中重复查询。和" ELSE",有没有办法让它成为单个查询而无需动态查询?

谢谢!

3 个答案:

答案 0 :(得分:0)

如果我的查询正确,您希望显示所有字段,即使CDPUserID不存在,或0对吗?您只需要在第二次加入中FULL JOIN

SELECT C.AwardId, C.ProgramName, Count(ClientId) as Intakes FROM Client C
INNER JOIN UserRoleEntity URE ON C.AwardId = URE.EntityId 
FULL JOIN UserRole UR ON URE.UserRoleId = UR.Id AND UR.CDPUserId = @UserId
     WHERE C.Id = @ClientId
     GROUP BY C.AwardId, C.ProgramName...

答案 1 :(得分:0)

在where条件

中使用OR和EXISTS()
select C.AwardId, C.ProgramName, Count(ClientId) as Intakes from Client C
where 
    (testFunction(@UserId)) = 0 
    OR 
    (
      EXISTS
      (
        SELECT * FROM UserRoleEntity URE INNER JOIN UserRole UR ON URE.UserRoleId = UR.Id AND UR.CDPUserId = @UserId
        WHERE C.AwardId = URE.EntityId 
      ) 
      AND C.Id = @ClientId
    )
group by C.AwardId, C.ProgramName...

答案 2 :(得分:0)

您可以使用其他WHERE条件和LEFT JOIN来有条件地过滤:

SELECT C.AwardId, C.ProgramName, Count(ClientId) as Intakes 
FROM Client C
LEFT JOIN UserRoleEntity URE ON C.AwardId = URE.EntityId 
LEFT JOIN UserRole UR ON URE.UserRoleId = UR.Id AND UR.CDPUserId = @UserId
WHERE C.Id = @ClientId
 AND (   testFunction(@UserId) = 0
      OR (testFunction(@UserId) <> 0 AND URE.AwardID IS NOT NULL AND UR.ID IS NOT NULL))
GROUP BY C.AwardId, C.ProgramName