T-SQL:测试条件如果匹配其他表,否则包括不测试

时间:2016-02-09 10:26:21

标签: sql sql-server subquery conditional where-clause

这是我尝试做的事情,但我无法正确理解语法:

SELECT 
    myKey1, myDate1
FROM 
    myTable1, 
    (SELECT myKey2, myDate2 FROM myTable2) as myDatesQuery
WHERE
    -- myTable1.myKey1 = myDatesQuery.myKey2 AND myTable1. myDate1 < myDatesQuery. myDate2
    -- OR myTable1.myKey1 not found in myDatesQuery

因此,如果myKey1在myDatesQuery中不存在,那么请包含它。如果myKey1 = myKey2只包括myDate1在myDate2之前。

非常感谢

1 个答案:

答案 0 :(得分:1)

尝试:

Select myTable1.myKey1, myTable1.myDate1
    FROM 
(SELECT myKey2, myDate2 FROM myTable2) as myDatesQuery
left outer join myTable1 
        on myTable1.myKey1 = myDatesQuery.myKey2
        where myTable1.myKey1 is null or myTable1.myDate1< myDatesQuery.MyDate2