简体   繁体   English

PHP的SQL查询选择月份和年份之间

[英]php sql query select between month and year

I want select SQL query in where condition between month and year. 我想在月份和年份之间的条件中选择SQL query in my database have field name months and years for store produce input of month and year. 在我的数据库中,字段名称是“月”和“年”,用于商店产生“月和年”的输入。 now I want search produce input in December,2015 to august 2016 This is my sql 现在我想在2015年12月到2016年8月之间进行搜索产生输入。这是我的sql

SELECT * FROM tbl_produce p WHERE p.status =0 AND ((p.months >='12' 
AND p.years>='2015') AND (p.months <='8' AND p.years<='2016)) ;

but result return NULL , I known my query not correct but how to correct it ? 但是结果返回NULL ,我知道查询不正确,但是如何更正呢?

Why not design your date column as date ? 为什么不将日期列设计为日期?

If you want to keep your current design, try this: 如果要保留当前的设计,请尝试以下操作:

SELECT * 
FROM tbl_produce
WHERE status = 0 
AND concat(years, if(months > 9, months, concat('0', months))) 
  BETWEEN '201512' AND '201608'

OR 要么

SELECT * 
FROM tbl_produce
WHERE status = 0 
AND (
  (years = 2015 AND months = 12) 
  OR 
  (years = 2016 AND months < 9)
)

Your SQL query is looking for result where p.months is equal to both 12 and 8, and where p.years is equal to both 2015 and 2016. 您的SQL查询正在寻找p.months等于12和8以及p.years等于2015和2016的结果。

To achieve the result you are looking for, replace the AND between the two sets of parenthesis with OR, to look like so: 为了获得您想要的结果,请将两组括号之间的AND替换为OR,如下所示:

SELECT * FROM tbl_produce p WHERE p.status =0 AND ((p.months >='12' AND p.years = '2015') OR (p.months <='8' AND p.years = '2016));

If I had access to your table structure I would run the test myself to confirm, but I do believe this to be the correct syntax for the result you are looking for. 如果可以访问您的表结构,则可以自己运行测试以进行确认,但是我相信这对于您要查找的结果来说是正确的语法。

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

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