通常,如果我想按日期范围对表格进行查询,我会这样做:
SELECT DISTINCT c.ID AS 'id' FROM CUST c
JOIN TICKET t ON s.ID = t.SALE_ID
WHERE c.ACTIVE_IND = 1
AND t.DELIV_DATE BETWEEN '01-01-2012' AND '01-02-2012'
ORDER BY t.DELIV_DATE DESC
现在我需要进行相同的查询但忽略年份,所以我可以说从2月28日到3月2日,年份并不重要。
我尝试修改查询:
SELECT DISTINCT c.ID AS 'id' FROM CUST c
JOIN TICKET t ON s.ID = t.SALE_ID
WHERE c.ACTIVE_IND = 1
AND MONTH(t.DELIV_DATE) BETWEEN ... AND ...
AND DAY(t.DELIV_DATE) ... BETWEEN ...
ORDER BY t.DELIV_DATE DESC
如果起始日期小于结尾,则上述查询可以正常工作。这意味着如果我从2月20日到2月28日这样做,它可以正常工作,但如果我去2月28日到3月2日它将无法正常工作。
我可以在单个查询中实现此解决方案吗?
答案 0 :(得分:11)
...
AND DATE_FORMAT(t.DELIV_DATE, '%m%d') BETWEEN '0101' AND '0201'
...
更新 - 处理在结束年度中循环的范围(将0101
和0201
替换为代表from
和to
的实际变量:
...
AND
(DATE_FORMAT(t.DELIV_DATE, '%m%d') BETWEEN '0101' AND '0201'
OR '0101' > '0201' AND
(DATE_FORMAT(t.DELIV_DATE, '%m%d') >= '0101' OR
DATE_FORMAT(t.DELIV_DATE, '%m%d') <= '0201'
)
)
...
答案 1 :(得分:0)
if ($dates[0] != '0000-00-00') {
if(str_replace('-','',substr($dates[0],4))<=str_replace('-','',substr($dates[1],4))){
$having[] = ' DATE_FORMAT(`birthday`, "%m%d") BETWEEN ? AND ?';
}else{
$having[] = ' DATE_FORMAT(`birthday`, "%m%d") >= ? OR
DATE_FORMAT(`birthday`, "%m%d") <= ?';
}
$params[] = str_replace('-','',substr($dates[0],4));
$params[] = str_replace('-','',substr($dates[1],4));
}
包括日期相同时的示例
答案 2 :(得分:-1)
让我们说2月28日到5月2日更复杂:
.... AND ((month(DELIV_DATE)=2 and day(DELIV_DATE)>=28) or (month(DELIV_DATE) between 3 and 4) or (month(DELIV_DATE)=5 and day(DELIV_DATE)<=2)