简体   繁体   中英

Date between 2 other dates, disregarding year

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

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)

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