mysql - 从 2 个表中选择条件

标签 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 |

我想获取所有行,以便从 table2 获取所有 order_row 行,这些行不存在于 table1order_row 来自 table2 的行,其时间戳在 table2 中比 table1 更新。并且仅检查 表 2timestamp 比 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` 

Demo here

编辑:如果您只想考虑 table2 中比 '2016-11-03' 更新的记录,则只需添加:

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

关于mysql - 从 2 个表中选择条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40423855/

相关文章:

php - Symfony2 Doctrine,通过外键连接表

c# - 向sql表中插入文本

PHP/PDO/MySQL : inserting into MEDIUMBLOB stores bad data

php - Symfony Doctrine 多对零关系

mysql - SQL 问题 : one to many relationship and EAV model

java - 当我在 Controller 中调用服务时,出现错误空指针异常

python - 使用子进程通过 Python 测试与 MySQL 的连接

php - 未捕获的异常 'PDOException' - 主机 'xxx' 不允许连接到此 MySQL 服务器

sql - 如何在表和查询上使用 SELECT 插入

sql - 检查重复项时的最佳自连接技术