简体   繁体   English

MySQL选择两个日期之间的所有日期

[英]MySQL select all dates between two dates

I have a table called schedules which contains columns day, month, year, etc. What I need is to select records between the $datefrom and $dateto. 我有一个名为schedules的表,其中包含日,月,年等列。我需要在$ datefrom和$ dateto之间选择记录。 Here is my code that does not work :( 这是我的代码不起作用:(

SELECT * FROM schedules WHERE CONCAT(year, month, day) BETWEEN $datefrom AND $dateto

Im not sure if this is correct. 我不确定这是否正确。 Please help. 请帮忙。

Like showdev already said in a comment, you have to cast the string that is returned from CONCAT() function to date. 就像showdev在评论中已经说过的一样,您必须强制转换从CONCAT()函数返回的字符串。 But consider, that no index can be used on this. 但是请考虑一下,对此不能使用任何索引。

I'd suggest you create an additional column in your table with the full date. 我建议您在表中创建一个完整日期的附加列。 I don't know if you separated the date into 3 columns out of performance reasons, but have a try, if only one column is enough for you. 我不知道您是否出于性能原因将日期分为3列,但是尝试一下,如果仅一列就足够了。 Usually it's fast enough (when indexed). 通常,它足够快(索引时)。

If you don't want to do that and want to use indexes (if they exist at all on those 3 columns) you would have to write the query like this: 如果您不想这样做并且想要使用索引(如果它们在这三列中都存在),则必须编写如下查询:

SELECT * FROM schedules WHERE 
`year` BETWEEN YEAR($datefrom) AND YEAR($dateto)
AND `month` BETWEEN MONTH($datefrom) AND MONTH($dateto)
AND `day` BETWEEN DAY($datefrom) AND DAY($dateto)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM