2016-11-04 55 views
1

我需要一个SQL查询,用于从两个表中选择多个条件。从条件中选择

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行不是从table2其时间戳是table2table1新出现在table1order_row行。而检测开关只能从table 2至极行timestamp较新,2016年11月3日 结果必然是:

order_row | 
---------- 
0001  | because timestamp is newer in table2 
0004  | because timestamp is newer in table2 
0005  | because it's not present in table1 

回答

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 ...) 
+0

感谢您的快速响应。我还有一个问题。例如,我如何在查询检查表2中时间戳比2016-11-03更新的行中添加条件。 – Kalle

+0

@Kalle您可以添加谓词't2.timestamp>'2016-11-03'',并将其与't2.timestamp> t1.timestamp'结合使用,以防您希望更新的记录*和*记录超过特定日期。 –

+0

现在所有的作品。谢谢。我必须学习更多的:) – Kalle