Mysql 从2个有条件的表中选择
我需要一个SQL查询,用于从2个表中选择多个条件Mysql 从2个有条件的表中选择,mysql,sql,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 | ------------------
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\u行
行,这些行在table1
中不存在,并且order\u行
行在table2
中的时间戳比table1
更新。并且只检查表2中时间戳
比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`
编辑:如果只想考虑表2
中比'2016-11-03'
更新的记录,只需添加:
t2.`timestamp` > '2016-11-03' AND ( ... other conditions here ...)
这应该做到:
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`
编辑:如果只想考虑表2
中比'2016-11-03'
更新的记录,只需添加:
t2.`timestamp` > '2016-11-03' AND ( ... other conditions here ...)
谢谢你的快速回复。我还有一个问题。例如,我如何添加查询检查表2中时间戳比2016-11-03新的行的条件。@Kalle您可以添加谓词t2.timestamp>“2016-11-03”
,并将其与t2.timestamp>t1.timestamp
组合,以防您需要更新的记录和超过特定日期的记录。@Kalle很高兴我能提供帮助,请如果此答案有助于您解决问题,请将其或任何其他答案标记为已接受。感谢您的快速回复。我还有一个问题。例如,我如何添加查询检查表2中时间戳比2016-11-03新的行的条件。@Kalle您可以添加谓词t2.timestamp>“2016-11-03”
,并将其与t2.timestamp>t1.timestamp
组合,以防您需要更新的记录和超过特定日期的记录。@Kalle很高兴我能提供帮助,请如果这个答案有助于您解决问题,请将其或任何其他答案标记为已接受。