简体   繁体   English

sql 日期在月份时间跨度

[英]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.我现在想 select 位于特定月份的所有条目。 So if the user chooses "June", I want to get all Entries than are available in June.因此,如果用户选择“六月”,我希望获得所有 Entries,而不是 6 月可用的条目。 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.我当然可以在结尾添加相同的内容,但是如果条目从 5 月开始并在 7 月结束,这仍然无济于事。 I could of course calculate timestamps and compare directly, but i want to select this for june of any year - not just one specific.我当然可以计算时间戳并直接比较,但我想 select 任何一年的六月 - 而不仅仅是一个特定的。 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.看起来它应该可以工作,但它很复杂,我很确定使用 function 月份意味着你不会遇到任何索引。

You can also rephrase it as:您也可以将其改写为:

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

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

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