简体   繁体   中英

sql Date in month time span

I have entries in my Table like

uid / start / end / value

I now want to select all entries which lie in a specific month. So if the user chooses "June", I want to get all Entries than are available in June. The start and end are saved as timestamp (cant change that). I found somthing like:

WHERE month(start)=5

This does work, but unfortunately it only gives me the entries that start in June. I Can of course add the same for the end, but this would still not help if an entry starts in may and ends in july. I could of course calculate timestamps and compare directly, but i want to select this for june of any year - not just one specific. I was thinking of something like:

WHERE month(start) <= 5 && month(end) >= 5

which would work fine with timestamps, but obviously this has a problem with year-breaks.

Is there a nice solution to do this without calculating all timestamps for the following years and creating a sick big query?

Ok i figured this out:

WHERE month(start)=5
OR month(end)=5
OR ( month(start)<=5 AND month(end) >= 5)
OR ( month(start)<=5 AND year(start)<year(end))
OR ( month(end)>=5 AND year(start)<year(end))

I think it is correct and works fine.

It looks like it should work, but it's quite convoluted, and I'm pretty sure the use of the month function means you won't be hitting any indices.

You can also rephrase it as:

where  start <= 1 Jun 2011 
and    end >= 1 Jul 2011

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