我需要一个SQL查询,从2个表中选择多个条件。
table1
order_row | timestamp |
-----------------------
0001 |2016-11-04 |
0002 |2016-11-04 |
0003 |2016-11-04 |
0004 |2016-11-03 |
0006 |2016-11-03 |
table2
order_row | timestamp |
-----------------------
0001 |2016-11-05 |
0002 |2016-11-04 |
0003 |2016-11-04 |
0004 |2016-11-04 |
0005 |2016-11-04 |
0006 |2016-11-02 |
我希望获取所有行,以便从order_row
获取所有table2
行,而table1
和order_row
行中不包含table2
行时间戳在table2
中比table1
更新。并且仅比2016-11-03更新table 2
timestamp
的行
结果必须是:
order_row |
----------
0001 | because timestamp is newer in table2
0004 | because timestamp is newer in table2
0005 | because it's not present in table1
答案 0 :(得分:5)
这应该这样做:
SELECT t2.*
FROM Table2 AS t2
LEFT JOIN Table1 AS t1
ON t2.order_row = t1.order_row
WHERE t1.order_row IS NULL OR t2.`timestamp` > t1.`timestamp`
修改:如果您只想要考虑table2
之前'2016-11-03'
以上的记录,则只需添加:
t2.`timestamp` > '2016-11-03' AND ( ... other conditions here ...)