Sql如何选择两个日期之间的日期和月份

时间:2017-01-09 12:25:45

标签: mysql sql

如何选择两个日期之间的日期和月份:

例如:31/12月是2016年12月26日至2017年1月2日

我的疑问:

select table2.*
from table1,
     table2
where table2.day between DAYOFMONTH(table1.date_start) and DAYOFMONTH(table1.date_end)
  and table2.month between MONTH(table1.date_start) and MONTH(table1.date_end)

table1(预订):

-id -date_start(date)-date_end(date)

1 | 2016-12-26 | 2017年1月2日

表2 :(食谱)

id |名字| day(int)|月(int)

1 | xxx | 31 | 12

1 个答案:

答案 0 :(得分:1)

看起来你正在使用MySQL。而不是单独检查月份和日期,而只是使用BETWEEN来表示您希望捕获其范围的两个点。

SELECT t1.*
FROM table1 t1
INNER JOIN table2 t2
    ON t1.some_col = t2.some_col
WHERE day_col BETWEEN '2016-12-26' AND '2017-01-02'

请注意,我还在您的查询中添加了一个连接条件,没有它就会进行交叉连接,很可能不是您想要的。

相关问题