简体   繁体   中英

Php, MySql select records within current year, month range

I'm trying to create a query to select records that fit current year month range. Here is my database table:

id      name        date_start  date_end
======================================
1       John        2016-05-20  2018-01-01
2       Peter       2017-02-02  2017-05-10
3       Mike        2015-02-02  2017-02-06

and my query:

SELECT  * FROM users 
WHERE YEAR(date_start) = 2017 
  AND MONTH(date_start) = 01 
  OR YEAR(date_end) = 2017 
  AND MONTH(date_end) = 01 

So basically I need to select all users where current year/month in this case 2017/01 is within start/end column range.

In above query, only John and Mike records should be selected.

I think you just want to find out which users have the date 2017-01-01 within their ranges, defined by the date_start and date_end . If so, then the following query should work:

SELECT *
FROM users
WHERE date_start <= '2017-01-01' AND date_end >= '2017-01-01'

Demo here:

SQLFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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