SQL连接另一个有条件的表

时间:2019-10-02 05:14:16

标签: sql sql-server join sql-in

我下面有两个表

service table

serviceid      serviceName     title   isrestricted
---           --------------  ------  ----------
1                  abc          t1     0
2                  asd          t2     1
3                  def          t3     0


serviceRestricted table

sampletype   serviceid
--------     ---------
a            2


output

 serviceid      serviceName     title   isrestricted
    ---           --------------  ------  ----------
    1                  abc          t1     0   
    3                  def          t3     0

请参见输出。对于Service id 2 isrestricted = 1,并且servicerestricted表中存在条目。因此serviceid 2在输出中不可见

2 个答案:

答案 0 :(得分:0)

Left Join应该解决您的问题,

select S.serviceid,S.serviceName,S.title,S.isrestricted
from @service S
Left Join @serviceRestricted SR on SR.serviceid = S.serviceid
where S.isrestricted = 1

Sample code here..

答案 1 :(得分:0)

我可以通过下面的查询来实现

select S.serviceid,S.serviceName,S.title,S.isrestricted
from service S
WHERE
((S.IsRestricted =1 and S.serviceid NOT IN (SELECT SERVICEID FROM servicerestricted WHERE SampleType=@SampleType) ) 
OR (S.IsRestricted is null OR S.isrestricted =0))