我有一个sqlite表,它包含以下列:
id | description | startYear | startWeek | endYear | endWeek
startYear,startWeek,endYear和endWeek都是整数
所以给定当前的周和年(例如第4周,2017年),如何搜索包含给定周和年的startYear,startWeek和endYear,endWeek的行?
我目前正试图通过UNION-ing几个选择查询来手动执行此操作,但我认为这样做效率不高,并且不太提太多代码(相对来说,如果有某种类型的话)内置查询来执行此操作)。
我的查询目前看起来像这样:
Select id, description
from myTable
where (:currentYear = startYear AND
(:currentWeek >= startWeek OR
:currentWeek <= endWeek ))
UNION
Select id, description
from myTable
where (:currentYear > startYear AND
:currentWeek <= endWeek )
UNION
Select id, description
from myTable
where (:currentYear < endYear AND
:currentWeek <= 53 )
UNION
Select id, description
from myTable
where (:currentYear < endYear AND
:currentWeek <= 53 )
UNION
Select id, description
from myTable
where (:currentYear < endYear AND
:currentWeek <= 53 )
UNION
Select id, description
from myTable
where (:currentYear = endYear AND
:currentWeek <= endWeek);
答案 0 :(得分:1)
当您查询表单时:
SELECT ... WHERE A
UNION
SELECT ... WHERE B
您可以轻松地将其转换为表单的单个查询:
SELECT ... WHERE A OR B
通过使用布尔代数的规则,可以进一步简化WHERE条件。
但是你当前的查询是错误的,所以最好从头开始构建一个新的查询。
你想要的是相当于:
SELECT ... WHERE currentTime BETWEEN startTime AND endTime;
现在,不是将时间比较分成两个字段,而是构造单个时间值会更容易。只需将年份乘以100
并将其与周相加即可得到201704
之类的值,该值可与任何其他此类值正确比较:
SELECT ...
WHERE :currentYear * 100 + :currentWeek
BETWEEN startYear * 100 + startWeek
AND endYear * 100 + endWeek;