简体   繁体   English

mysql选择日期之间

[英]mysql select dates between

I have a single mysql table called prices storing dates from and to like so: 我有一个名为价格的mysql表,它存储日期从和这样:

id    from          to              price
1     2013-11-25    2014-01-08      55

the user selects a month and a year and i want it to show all results that either are from or to that month so if the user selected either november 2013, december 2013 or january 2014 it would include the above row. 用户选择一个月和一年,我希望它显示该月的所有结果,因此,如果用户选择2013年11月,2013年12月或2014年1月,则将包括上面的行。

id    from          to              price
2     2013-10-25    2013-11-07      100

and if they selected either october or november 2013 it would show the above row because it starts in october and ends november. 如果他们选择了2013年10月或2013年11月,则会显示上面的行,因为该行始于10月,结束于11月。

i have tried 我努力了

SELECT * FROM `prices`
WHERE MONTH(prices.from)<={$_SESSION['month']}
AND MONTH(prices.to)>={$_SESSION['month']}
AND YEAR(prices.to)={$_SESSION['year']}
ORDER BY prices.from ASC

which doesn't work i'm not sure how this can be done 这不起作用,我不确定该怎么做

You could use STR_TO_DATE to create a date from the month and year the user selects and then use DATE_FORMAT to put your table's date column in YYYY-MM format and compare both with the YYYY-MM the user inserted. 您可以使用STR_TO_DATE从用户选择的月份和年份创建日期,然后使用DATE_FORMAT以YYYY-MM格式放置表格的日期列,并将两者与用户插入的YYYY-MM进行比较。

I'm not fluent in php, but here's an example in sql (you can use any day in the str_to_date, since you will ignore it): 我不精通php,但是这是sql中的示例(您可以在str_to_date中使用任何一天,因为您会忽略它):

SELECT * FROM `prices`
WHERE DATE_FORMAT(prices.`from`,"%Y-%m") <= 
   DATE_FORMAT(STR_TO_DATE('01,10,2013','%d,%m,%Y'),"%Y-%m")
AND DATE_FORMAT(prices.`to`,"%Y-%m") >= 
   DATE_FORMAT(STR_TO_DATE('01,10,2013','%d,%m,%Y'),"%Y-%m")
ORDER BY prices.`from` ASC

sqlfiddle demo sqlfiddle演示

Try to use "BETWEEN" instead. 尝试改用“ BETWEEN”。 example: 例:

SELECT * FROM `prices` WHERE MONTH(`from`) BETWEEN '10' AND '12' AND YEAR(`to`)='2013'

Follow this method: 请遵循以下方法:

SELECT * from prices
WHERE str_to_date('{$_SESSION['month']}-{$_SESSION['year']}','%b-%Y') BETWEEN date(prices.from) AND date(prices.to)

You might just want to use the correct format in the str_to_date, currently it converts the following format = Oct-2013 您可能只想在str_to_date中使用正确的格式,当前它会转换以下格式= 2013年10月

Check this for other formats: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_str-to-date 检查其他格式: http : //dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_str-to-date

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

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