[英]Sql - find if date is between two dates
我有一個FromDate字段和一個ToDate字段。
我正在尋找今天在“從”到“到”之間的行
select * from job
where job.type='manager'
and '2014-01-22' between job.FromDate and job.ToDate
查詢不會引發異常,它甚至返回一些行。 但這是不對的,它返回的行沒有我要查找的日期。
PS我使用的日期格式對於我的數據庫是正確的。
嘗試這個
select * from job
where job.type='manager'
and job.FromDate <= '2014-01-22' and job.ToDate >= '2014-01-22'
比較日期通常很棘手,尤其是當值存儲為datetime
而不是date
。 時間成分會影響比較。 另一種可能性是,對於最新記錄, ToDate
為NULL。 這是解決此問題的一種方法:
select *
from job
where job.type ='manager' and
date('2014-01-22') between date(job.FromDate) and date(coalesce(job.ToDate, '2099-12-31'))
但是,在列上使用該函數會使查詢效率降低。 相反,您可以嘗試:
select *
from job
where job.type ='manager' and
job.FromDate < '2014-01-23' and
(job.ToDate >= '2014-01-22' or job.ToDate is null);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.