MySql通过其他元素从两个不同的表中选择id然后是id

时间:2017-04-10 14:53:32

标签: mysql

我有两个表tableAtableB,它们都有字段id, code, validFromvalidUntil。我正试图从女巫tableA.code = tableB.codetableA.validFrom = tableB.validFromtableB.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

2 个答案:

答案 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) )