Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL:在日期之间进行选择_Sql_Database - Fatal编程技术网

SQL:在日期之间进行选择

SQL:在日期之间进行选择,sql,database,Sql,Database,我有两张桌子,看起来像: table A: ID, target_date, target_ID table B: ID, target_ID, begin_date, end_date 表B可能有多条相同目标ID但日期范围不同的记录。我对SQL查询感兴趣,该查询能够返回不在给定目标ID的开始日期和结束日期范围内的目标日期。选择一个目标日期 SELECT A.target_date FROM A LEFT OUTER JOIN B ON (A.target_ID=B.targe

我有两张桌子,看起来像:

table A:
ID, target_date, target_ID

table B:
ID, target_ID, begin_date, end_date
表B可能有多条相同目标ID但日期范围不同的记录。我对SQL查询感兴趣,该查询能够返回不在给定目标ID的开始日期和结束日期范围内的目标日期。

选择一个目标日期
SELECT A.target_date 
FROM A LEFT OUTER JOIN B 
     ON (A.target_ID=B.target_ID 
     AND A.target_date>=B.begin_date 
     AND A.target_date<=B.end_date) 
WHERE B.begin_date IS NULL
从A左外接B 打开(A.target\u ID=B.target\u ID A.目标日期>=B.开始日期 和A.target\u date
选择A.target\u date
从A左外接B
打开(A.target\u ID=B.target\u ID
A.目标日期>=B.开始日期

A.target_date有一个技巧。使用
左连接查找匹配的,然后选择不匹配的:

select a.*
from tablea a left join
     tableb b
     on a.target_id = b.target_id and
        a.target_date between b.begin_date and b.end_date
where b.target_id is null;
您可以用几种不同的方式来表达这一点。例如,
不存在
似乎也很自然:

select a.*
from tablea a
where not exists (select 1
                  from tableb b
                  where a.target_id = b.target_id and
                        a.target_date between b.begin_date and b.end_date
                 );

注意:我使用
之间进行这些比较,作为一种方便的速记(与您在问题中使用的语言相匹配)。通常在日期时,最好明确使用
=

有一个技巧。使用
左连接查找匹配的,然后选择不匹配的:

select a.*
from tablea a left join
     tableb b
     on a.target_id = b.target_id and
        a.target_date between b.begin_date and b.end_date
where b.target_id is null;
您可以用几种不同的方式来表达这一点。例如,
不存在
似乎也很自然:

select a.*
from tablea a
where not exists (select 1
                  from tableb b
                  where a.target_id = b.target_id and
                        a.target_date between b.begin_date and b.end_date
                 );
注意:我在这些比较中使用了
作为一种方便的速记(以匹配您在问题中使用的语言)。通常在日期时,首选显式使用
=

可能:

SELECT target_date FROM A 
   INNER JOIN B 
   ON A.target_ID = B.target_ID
WHERE target_date NOT BETWEEN begin_date AND end_date
也许:


你能提供你已经尝试过的示例吗?可能没那么重要,但是你应该为你正在使用的DBMS(Postgres,Oracle,…)添加一个标记。你能提供你已经尝试过的示例吗?可能没那么重要,但是你应该为你正在使用的DBMS(Postgres,Oracle,…)添加一个标记