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.

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

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大