complex query join checking that value does not exist

青春壹個敷衍的年華 提交于 2019-12-12 01:25:37

问题


I am struggling with a great challenge of a query. I have two tables, first has

Tb1 drID schedDate rteID

Second has:

Tb2 drID FName LName Active

Tb1 drID must be checked for Null or blank and match on schedDate and drID can not have any values that match Tb2.drID for date selected, checking for Null and '' essentially do this.

SELECT drID, schedDate, rteID
FROM            Tb1
WHERE        (drID IS NULL OR drID = '') AND (schedDate = 11 / 1 / 2012)

From all of this I need to return from TB2 drID, Fname, LName Where Active = True and drID does not exist on any record in tb1 for the schedDate selected.

There are many tb1 rteID records for any possible date.

Thank you for any help on this and huge Holiday Thank You.


回答1:


Can you make your select statement a subquery for example:

SELECT drID, Fname, LName
FROM   TB2
WHERE  Active = True 
 AND   drID NOT IN (
       SELECT drID
       FROM   Tb1
       WHERE  (drID IS NULL OR drID = '')
        AND  (schedDate = 11 / 1 / 2012)
       )

Edit
To handle the case that the schedDate is null then

SELECT drID, Fname, LName
FROM   TB2
WHERE  Active = True 
 AND   drID NOT IN (
       SELECT drID
       FROM   Tb1
       WHERE  (drID IS NULL OR drID = '')
        AND  (schedDate = @yourDate OR schedDate IS NULL)
       )

Edit 2
To handle the case that the drID is null then you can use the NOT EXISTS approach as highlighted in this SO post about NOT IN vs NOT EXISTS

SELECT drID, Fname, LName
FROM   TB2
WHERE  Active = True 
 AND   NOT EXISTS (
       SELECT drID
       FROM   Tb1
       WHERE  (schedDate = @yourDate) 
        AND   Tb1.drID = TB2.drID
       )


来源:https://stackoverflow.com/questions/13992879/complex-query-join-checking-that-value-does-not-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!