识别两个表之间的新条目

时间:2019-04-13 03:49:50

标签: mysql

我想标识表T1中最近的条目(自60天以来),这些条目不在另一个表T2中。

由于MySQL不支持'FULL OUTER JOIN',因此我尝试了以下代码。

我希望从T1中找到一条记录,该记录已从T2中删除。当前代码无法产生预期的结果。

怎么了?

SELECT * FROM (

  SELECT store, name, date
  FROM `T1` A
  LEFT JOIN `T2` V
    ON A.name=V.namebis AND A.store=V.storebis

  UNION ALL 

  SELECT store, name, date
  FROM `T1` A
  RIGHT JOIN `T2` V
    ON A.name=V.namebis AND A.store=V.storebis
  WHERE A.name is null

) C
WHERE store IN (NYC, CHICAGO)
  AND (date BETWEEN CURRENT_DATE AND subdate(CURRENT_DATE, 60))
GROUP BY store, name

2 个答案:

答案 0 :(得分:2)

如果只想检查T1中的哪些条目不再在T2中,则不需要FULL JOIN,只需使用LEFT JOIN并通过检查T2中的字段是否为T2,来检查NULL中行是否不再存在。请注意,BETWEEN子句中的值顺序是错误的,最低值必须是第一个。我也将其固定在下面。

SELECT store, name, date
FROM T1 
LEFT JOIN T2 ON T1.name = T2.namebis AND T1.store = T2.storebis
WHERE store IN (NYC, CHICAGO)
  AND (date BETWEEN subdate(CURRENT_DATE, 60) AND CURRENT_DATE)
  AND T2.namebis IS NULL

答案 1 :(得分:1)

尝试一下:

SELECT store, name, date
FROM T1 
LEFT JOIN T2 
ON (T1.name = T2.namebis AND T1.store = T2.storebis)
WHERE store IN (NYC, CHICAGO)
  AND TIMESTAMPDIFF(DAY, DATE(T1.`date`),CURDATE()) =60
  AND T2.namebis IS NULL