SQL查询以选择表中所有不存在于不同表的开始和结束时间字段中的行?

时间:2019-04-10 06:34:20

标签: sql datetime presto

我有table1我要返回的行,这些行在表2中相同的ids开始和结束时间戳字段中不存在。我在下面进行查询,但它返回0行。我看不到我在做什么错吗?

SELECT table1.*
FROM table1
WHERE table1.day = date '03-04-19'
  AND NOT EXISTS
    (SELECT NULL
     FROM table2
     WHERE table1.id = table2.id
       AND table1.timestamp >= table2.start_time
       AND table1.timestamp <= table2.end_time)

3 个答案:

答案 0 :(得分:1)

也许您的问题仅仅是日期格式:

SELECT table1.*
FROM table1
WHERE table1.day = date '2019-04-03' AND
     NOT EXISTS (SELECT 1
                 FROM table2
                 WHERE table1.id = table2.id AND
                       table1.timestamp >= table2.start_time AND
                       table1.timestamp <= table2.end_time
                 );

答案 1 :(得分:0)

尝试如下

  SELECT t1.*
    FROM table1 t1
    WHERE table1.day = date '03-04-19'
      AND NOT EXISTS
        (SELECT 1
         FROM table2 t2
         WHERE t1.id = table2.id
           AND t1.timestamp >= t2.start_time
           AND t1.timestamp <= t2.end_time)

答案 2 :(得分:-1)

我不明白为什么要使用> =和<=。但是,您可以尝试以下方法:

SELECT table1.*
FROM table1
LEFT JOIN
table2
ON
table1.id = table2.id
AND table1.timestamp >= table2.start_time
AND table1.timestamp <= table2.end_time
WHERE table1.date = CAST('03-04-19' as DATE)
AND table2.id IS NULL