我的查询如下
SELECT ajd.Make, ajd.Model, ajd.Filter, ajd.Notes, ajd.CatamacPartNumber, ajd.FromDate, ajd.ToDate
FROM ApplicationJapData ajd
WHERE ajd.Model LIKE '%FVR34%'
AND FromDate <= '20140701' AND ToDate >= '20140701'
此查询的作用是根据包含特定搜索字符串的Model
选择行,其中提供的日期位于FromDate
列和ToDate
列之间。
问题是有时候ToDate是null
,因为它取决于当前日期(例如,FromDate
= 1/1/2015
,而ToDate
是{{1}因为它是null
- 1/1/12
)
因此,如果我提供12-12-2015的值,我仍然希望在符合Present
条件的情况下返回行。
但是,我无法在FromDate
中使用OR
因为FromDate <= '20140701' OR ToDate >= '20140701'
可能有ToDate
,在这种情况下,1-6-15
非常感谢任何帮助,请询问是否有任何不清楚或需要澄清的事情!
答案 0 :(得分:2)
AND FromDate <= '20140701'
AND (ToDate is null OR ToDate >= '20140701')
答案 1 :(得分:1)
规范方法是:
SELECT ajd.Make, ajd.Model, ajd.Filter, ajd.Notes, ajd.CatamacPartNumber, ajd.FromDate, ajd.ToDate
FROM ApplicationJapData ajd
WHERE ajd.Model LIKE '%FVR34%' AND
FromDate <= '20140701' AND (ToDate >= '20140701' or ToDate IS NULL)
或:
WHERE ajd.Model LIKE '%FVR34%' AND
FromDate <= '20140701' AND
coalesce(ToDate, '20140701') >= '20140701'
在某些情况下,您可能希望选择一个遥远的未来日期作为结束日期 - 因此该值永远不会是NULL
。这有助于鼓励使用表的查询使用索引。
答案 2 :(得分:0)
最简单的解决方案是将to_date与远期日期合并,例如
SELECT ajd.Make, ajd.Model, ajd.Filter, ajd.Notes, ajd.CatamacPartNumber, ajd.FromDate, ajd.ToDate
FROM ApplicationJapData ajd
WHERE ajd.Model LIKE '%FVR34%'
AND FromDate <= '20140701' AND coalesce(ToDate,'99991231') >= '20140701'
答案 3 :(得分:0)
实现逻辑的最简单方法是明确允许迄今为止的所有NULL
值:
SELECT ajd.Make,
ajd.Model,
ajd.Filter,
ajd.Notes,
ajd.CatamacPartNumber,
ajd.FromDate,
ajd.ToDate
FROM ApplicationJapData ajd
WHERE ajd.Model LIKE '%FVR34%' AND
FromDate <= '20140701' AND (ToDate >= '20140701' OR ToDate IS NULL)
答案 4 :(得分:0)
与上述答案类似。 IsNull
performs better than the generic Coalesce
并且优于另一个AND
。
SELECT ajd.Make,
ajd.Model,
ajd.Filter,
ajd.Notes,
ajd.CatamacPartNumber,
ajd.FromDate,
ajd.ToDate
FROM ApplicationJapData ajd
WHERE ajd.Model LIKE '%FVR34%'
AND FromDate <= '20140701'
AND IsNull(ToDate,'99991231') >= '20140701'