从2个有条件的表中选择

时间:2016-11-04 13:26:09

标签: mysql sql

我需要一个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行,而table1order_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

1 个答案:

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

Demo here

修改:如果您只想要考虑table2之前'2016-11-03'以上的记录,则只需添加:

t2.`timestamp` > '2016-11-03' AND ( ... other conditions here ...)