我有两个表tableA
和tableB
,它们都有字段id, code, validFrom
和validUntil
。我正试图从女巫tableA.code = tableB.code
,tableA.validFrom = tableB.validFrom
和tableB.validUntil = Null && tableA.validUntil != Null
中的两个表中获取ID。
我尝试了一个带内连接的选择
Select a.id, b.id from tableA as a
inner join tableB as b ON
(a.code = b.code and a.validFrom = b.validFrom)
where b.validUntil is Null and a.validFrom != Null
但是我得到0结果。 表格示例
TableA
id | code | validFrom | validUntil | Extra
---------------------------------------------
1 | ABCD | 2010-01-01 | 2016-01-01 | NULL
2 | EFA | 2010-01-01 | 2015-01-01 | 12
3 | FAS | 2012-01-01 | 2017-01-01 | 13
并且
TableB
id | code | validFrom | validUntil | Extra
---------------------------------------------
1 | EFA | 2010-01-01 | NULL | 12
2 | ABCD | 2010-01-01 | NULL | NULL
3 | FAS | 2012-01-01 | 2017-01-01 | 13
所以结果应该是
TableA.id | TableB.id
---------------------
1 | 2
2 | 1
编辑:
Select a.id, b.id from tableA as a
left join tableB as b ON
a.code = b.code
and a.validFrom = b.validFrom
and a.Extra = b.Extra
where b.validUntil is Null
and a.validFrom is not Null
答案 0 :(得分:1)
使用IS NOT NULL
代替!= null
。您不必在DB中使用具有NULL
值的相等运算符。更改以下条件
and a.validFrom != Null
到此
and a.validFrom is not Null
再次使用LEFT JOIN
代替
Select a.id, b.id from tableA as a
left join tableB as b ON
a.code = b.code
and a.validFrom = b.validFrom
where b.validUntil is Null
and a.validFrom is not Null
答案 1 :(得分:0)
是的,我想做的与@Rahul所说的相似
Select a.id, b.id from tableA as a
left join tableB as b ON
a.code = b.code
and a.validFrom = b.validFrom
where b.validUntil is Null
and a.validFrom is not Null
and (a.Extra = b.Extra or (a.Extra is NULL and b.Extra is NULL) )