如何根据日期连接两个表? MYSQL

How to join two tables based on date? MYSQL

我正在尝试加入两个都具有检查日期的 table。仅当第一个 table 中的检查日期与第二个 table 中的检查日期相同时,才会显示结果。或者,如果两个 table 中的检查日期相差在 10 天内。

我有两个 table:

t1 table: company_id, expected_checkdate

t2 table: company_id, actual_checkdate

问题是我运行这个一个月了。我看到很多重复项,因为一个月内可能有 2 个 actual_checkdate 条目或 2 个 expected_checkdate。

      |---------------------|------------------|------------------|
      |     company_id      | actual_checkdate |expected_checkdate|
      |---------------------|------------------|------------------|
      |          12         |    2018-01-05    |    2018-01-05    |
      |---------------------|------------------|------------------|
      |          12         |    2018-01-19    |    2018-01-19    |
      |---------------------|------------------|------------------|
      |          12         |    2018-01-05    |    2018-01-19    | -- incorrect 
      |---------------------|------------------|------------------|
      |          12         |    2018-01-19    |    2018-01-05    | -- incorrect 
      |---------------------|------------------|------------------|
      |          13         |    2018-01-12    |    2018-01-20    | 
      |---------------------|------------------|------------------|
      |          14         |    2018-01-26    |    2018-01-36    | 
      |---------------------|------------------|------------------|

前两行和后两行是正确的。第三行和第四行不应显示,因为它们与第一行和第二行重复。请帮助我完成上面的连接。

您可以将您的 JOIN 条件重写为:

FROM t1
JOIN t2 ON t1.company_id = t2.company_id AND
   (t1.actual_checkdate = t2.expected_checkdate OR
    t1.actual_checkdate BETWEEN 
       DATE_SUB(t2.expected_checkdate, INTERVAL 10 DAY) 
       AND DATE_ADD(t2.expected_checkdate, INTERVAL 10 DAY)
    AND NOT EXISTS (SELECT * FROM t1 WHERE t1.actual_checkdate = t2.expected_checkdate AND t1.company_id = t2.company_id)
 )

如果存在实际匹配,则 NOT EXISTS 子句将阻止在临近日期进行匹配。