我需要一个 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 |
我想获取所有行,以便从 table2
获取所有 order_row
行,这些行不存在于 table1
和 order_row
来自 table2
的行,其时间戳在 table2
中比 table1
更新。并且仅检查 表 2
中 timestamp
比 2016-11-03 更新的行。
结果必须是:
order_row |
----------
0001 | because timestamp is newer in table2
0004 | because timestamp is newer in table2
0005 | because it's not present in table1
最佳答案
应该这样做:
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 ...)
关于mysql - 从 2 个表中选择条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40423855/