简体   繁体   中英

Range query from month and year

I have a table like this:

ID  month    year   content
1     4      2013    xxxxx
2     5      2013    yyyyy
3     6      2013    zzzzz
4     8      2014    fffff

I want to query it based on a year and month range.

I have query like this:

SELECT * FROM UPP 
WHERE ( month = '4' AND year = '2013' )
  AND ( month = '6' AND year = '2013' ) 

That query runs but returns no result. Can anyone help me for fix this query?

NB: The month and year columns are integers.

Why not use the correct data type?

Failing that:

SELECT * FROM UPP WHERE (year=2013) AND (month BETWEEN 4 AND 6);

Would be the easiest path to this particular answer.

EDIT

SQL Fiddle for reference.

There will never be any rows where both month=4 and month=6 which is what your query is asking for. Adding brackets like that will not alter the AND behaviour as you seem to want them to so you are asking for WHERE year=2013 AND month=4 AND month=6 .

There are a number of ways you could ask for what you seem to be wanting, for instance:

WHERE (year=2013 AND month=4) OR (year=2013 AND month=6)

or

WHERE year=2013 AND (month=4 OR month=6)

or

WHERE year=2013 AND month IN (4,6)

If you want the full range (the full quarter, months 4, 5, and 6 not just months 4 and 6 then swasheck's suggestion is probably the clearest way to go, though this will fall down if the date range straddles a boundary between years. If you need to do fully flexible ranged queries ("the six months to February 2013" and so forth) then you might want to rethink the table structure to more easily/efficiently support that.

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