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,…)添加一个标记