Date between 2 other dates, disregarding year

无人久伴 提交于 2019-12-31 04:27:07

问题


I'm looking for something like the person here was lookin for, only I'd like to use MySQL. The table below is something you'd find in my database (simplified).

+------+------+------+------+
| id   | name | first| last |
+------+------+------+------+
|    1 | John | 1020 | 0814 |
|    2 | Ram  | 0827 | 0420 |
|    3 | Jack | 0506 | 0120 |
|    4 | Jill | 0405 | 0220 |
|    5 | Zara | 1201 | 1219 |
+------+------+------+------+

First of all the entry has to be random, not id 4 and I only want 1 entry. I worked that out: SELECT * FROM test WHERE id <> 4 ORDER BY rand() LIMIT 1.

In this table the columns 'first' and 'last' are dates formatted as mmdd (both integers). So John is available for most of the year; from October 20th to August 14th. Zara on the other hand is only available for a small period of time; December 1st till December 19th.

My question: how do I change my query to only select the available people? I can't use 'between' since, in John's case, there's nothing between 1020 and 0814.

I just can't figure it out, there's must be other people that have a similar problem... Does anyone have a solution?

Kind regards


回答1:


You need to distinguish two cases.

  1. When first < last, the dates are in the same year. You can then use between to match dates.

  2. When first > last, it means last is in the next year. In this case, the dates that match are date >= first OR date <= last.

So your WHERE clause should be:

WHERE IF(first < last, @date BETWEEN first AND last,
                       @date >= first OR date <= last)


来源:https://stackoverflow.com/questions/18294786/date-between-2-other-dates-disregarding-year

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!