2016-11-04 54 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