仅在mysql中使用月份和年份从两个表中选择数据

时间:2014-01-06 05:00:20

标签: mysql

Entered-month  Entered-year  Amount
-------------------------------------
01             2013        3000
02             2013        4000
.               .           .
.               .           .
.               .           .
01             2014        2000

我的桌子是这样的 我必须在两个日期之间获取数据量 对于ex 01/11/2011至03/01/2014

1 个答案:

答案 0 :(得分:0)

使用MySQL函数STR_TO_DATECONCAT将月份和年份字段作为日期放在一起。 http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_str-to-date http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_concat

select Amount
from tbl1
where STR_TO_DATE(CONCAT(tbl1.Entered-month,'-',tbl1.Entered-year),'%m-%Y') >= [start date] 
    and STR_TO_DATE(CONCAT(tbl1.Entered-month,'-',tbl1.Entered-year),'%m-%Y') <= [end date]

OR

select Amount
from tbl1
where STR_TO_DATE(CONCAT(tbl1.Entered-month,'-',tbl1.Entered-year),'%m-%Y') 
    between [start date] and [end date]

确保[start date][end date]在传递到查询时的日期格式正确。如果这些参数是字符串参数,请对STR_TO_DATE使用。

select Amount
from tbl1
where STR_TO_DATE(CONCAT(tbl1.Entered-month,'-',tbl1.Entered-year),'%m-%Y') 
    between STR_TO_DATE(startDate,'%Y-%m-%d') and STR_TO_DATE(endDate,'%Y-%m-%d')