如何在本月1日至上月17日之间进行选择



我使用这个选择查询,但在下个月之后,上个月的数据就不会来了。

SELECT xxx,xxx,xxx 
FROM lott_user_table 
WHERE MONTH(NOW()) AND DAYOFMONTH(datetime) BETWEEN 17 AND 1

如何修复或获取本月1日至上月17日之间的数据(不使用date_sub(((?

谢谢你(对不起我的英语(

SELECT id,datetime
FROM lott_user_table 
where MONTH(datetime) between MONTH(CURRENT_DATE - INTERVAL 1 MONTH) 
and MONTH(CURRENT_DATE)
and (DAYOFMONTH(datetime) > case when MONTH(datetime) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)  then 
17
end
or DAYOFMONTH(datetime) <= case when MONTH(datetime) = MONTH(CURRENT_DATE)  then 
1
end)

这是演示:

演示

n between 17 and 1永远不会返回任何行,因为它等价于n >= 17 and n <=1,这根本不可能。

您应该尝试使您的条件可搜索,即避免在比较的两侧进行计算:

-- get the 17th of the previous month
-- = 1st of current month - 1 month + 16 days
where datetime between subdate(CURRENT_DATE, dayofmonth(current_date)-1) - interval 1 month + interval 16 day
-- 1st of current month
and subdate(CURRENT_DATE, dayofmonth(current_date)-1)

参见小提琴

最新更新