我有2张桌子(下面的样本)
aTable
-------------------------------------------------
name | datein | dateout
test | 2016-10-10 00:00:00 | null --->> This one
test2 | 2016-10-12 00:00:00 | null
-------------------------------------------------
bTable
------------------------------------------------------------
name | datein | dateout
test | 2016-05-05 00:00:00 | 2016-06-06 00:00:00
test | 2016-10-10 00:00:00 | null --->> This one
test2 | 2016-10-12 00:00:00 | 2016-10-13 00:00:00
------------------------------------------------------------
我想提取name
,datein
相等且dateout
null
我正在使用下面的查询,但我得到空的回复。
SELECT name,datein
FROM aTable
WHERE (name = 'test' AND dateout IS NULL) AND
(SELECT name FROM bTable WHERE name = 'test' AND dateout IS NULL)
我缺少什么意思?
答案 0 :(得分:2)
您需要在查询中添加EXISTS
:
SELECT t1.name, t1.datein
FROM aTable AS t1
WHERE (t1.name = 'test' AND t1.dateout IS NULL) AND
EXISTS(SELECT name
FROM bTable AS t2
WHERE t2.name = 'test' AND
t2.datein = t1.datein AND
t2.dateout IS NULL)
或者,没有为name
字段提供特定值:
SELECT t1.name, t1.datein
FROM aTable AS t1
WHERE t1.dateout IS NULL AND
EXISTS(SELECT name
FROM bTable AS t2
WHERE t2.name = t1.name AND
t2.datein = t1.datein AND
t2.dateout IS NULL)
答案 1 :(得分:1)
试试这个
SELECT name,datein,dateout FROM(select * from atable union select * from btable)as tt
where tt.name ='test' and tt.dateout is null;