douren6874 2012-04-20 08:03
浏览 516
已采纳

Mysql查询匹配的月份和年份

I have form with 4 fields namely(start month, start year, end month, end year) and MySQL table structure is like id, customer id, amount, month, year

Now, I need to display the rows with matching condition as between the start month and year and end month and year.

I tried this query

select id,customer id,concat(month,'-',year) as d1 from payroll where
empid='$_POST[emp_id]' and (STR_TO_DATE(d1,'%m-%Y') between
STR_TO_DATE('$_POST[fmonth]-$_POST[fyear]','%m-%Y') and
STR_TO_DATE('$_POST[tmonth]-$_POST[tyear]','%m-%Y'))

Please advise....

  • 写回答

1条回答 默认 最新

  • doukou1718 2012-04-20 08:35
    关注

    Assuming the columns year and month and the 4 form fields are integers, this would work:

    SELECT id
         , customer id
         , CONCAT(month, '-', year) AS d1 
    FROM payroll 
    WHERE empid = '$_POST[emp_id]' 
      AND (year, month) >= ( '$_POST[fyear]', '$_POST[fmonth]' ) 
      AND (year, month) <= ( '$_POST[tmonth]', '$_POST[tyear]' )
    

    You should probably take care of those $_POST[] before sending them to the database for security reasons (SQL injection).

    A compound index on (empid, year, month) would help performance.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决