SQL检查月份在两个日期之间

时间:2018-10-29 09:15:14

标签: mysqli

SELECT * FROM bookingpoleorder WHERE ((
   YEAR(sDate) = $year AND MONTH(sDate) = $month
) OR (
   YEAR(eDate) = $year AND MONTH(eDate) = $month
))

我有一个预订表,其中包含两个日期,例如开始日期和结束日期。所以我需要获得一个月所有预订的报告。以下是我使用的查询。但是如果日期是 从2018-09-122018-12-12的预订仅在第9个月显示,并且 第12个月不在两个月之间

4 个答案:

答案 0 :(得分:1)

BETWEEN运算符选择给定范围内的值。这些值可以是数字,文本或日期。

SELECT * FROM bookingpoleorder 
WHERE sDate BETWEEN '2018-09-12' AND '2018-12-12' 
OR eDate BETWEEN '2018-09-12' AND '2018-12-12' 

或使用between

SELECT * 
FROM bookingpoleorder
WHERE date_to_compare BETWEEN  sDate AND eDate

答案 1 :(得分:0)

SELECT * 
FROM bookingpoleorder
WHERE CAST($month AS DATE) BETWEEN  CAST(sDate AS DATE) AND CAST(eDate AS DATE)

答案 2 :(得分:0)

这完全取决于您拥有的数据库。如果您使用的是mysql,请尝试

SELECT * FROM bookingpoleorder WHERE DATE_FORMAT(date,'%Y')=$year AND DATE_FORMAT(date,'%m') BETWEEN $month1 AND $month2

答案 3 :(得分:0)

如果sdate是开始日期,edate是结束日期,您将提供$year作为年份,$month作为月份,然后尝试:

SELECT * FROM bookingpoleorder WHERE DATE_FORMAT(sdate,'%Y') = $year AND DATE_FORMAT(edate,'%Y') = $year AND DATE_FORMAT(sdate,'%m') = $month AND DATE_FORMAT(edate,'%m') = $month