我正在尝试连接两个表,这两个表都有check date。仅当第一个表中的检查日期等于第二个表中的检查日期时,结果才应显示。或者如果两个表中的检查日期都在10天之内。
我有两张table:
t1 table: company_id, expected_checkdate
t2 table: company_id, actual_checkdate
条件1:acutal\u checkdate=预期的\u checkdate
条件2:实际检查日期在预期检查日期的10天内
条件3:预期检查日期在实际检查日期的10天内
条件4:如果acutal\u checkdate=预期的\u checkdate,则不检查10天内的其他人
LEFT OUTER JOIN t2 ON t1.actual_checkdate = t2.expected_checkdate
OR t1.actual_checkdate
BETWEEN DATE_ADD(t2.expected_checkdate, INTERVAL -10 DAY)
AND DATE_ADD(t2.expected_checkdate, INTERVAL 10 DAY)
AND t1.company_id = t2.company_id
问题是当我运行这个一个月。我看到了很多重复项,因为一个月内可能有两个实际的\u checkdate条目或两个预期的\u 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 |
|---------------------|------------------|------------------|
前两行和后两行是正确的。第三行和第四行不应显示,因为它们是第一行和第二行的副本。请帮我做上面的连接。
1条答案
按热度按时间j7dteeu81#
你可以重写你的
JOIN
条件为:如果存在实际的匹配,notexists子句将阻止在附近的日期进行匹配。