LoginSignup
16
15

More than 5 years have passed since last update.

SQLで開店時間と閉店時間などを条件とする際、日付をまたぐケースがある場合

Last updated at Posted at 2014-04-02

とりあえずメモ。
時間が空いたときに書き直して整理する。

SQLで開店時間と閉店時間などを条件とする際、日付をまたぐケースがある場合、単純に大小比較やBETWEENでは比較できないので、少しややこしくなる。

多分、こんな感じになるとおもう。

-- お店が18:00:00に開いているかを調べる場合
SELECT
    shop.shop_id,
    shop.shop_name
    shop.open_time,
    shop.close_time
FROM
    shop
WHERE
    (
        (shop.open_time < shop.close_time -- exp: 10:00 - 22:00
            AND '18:00:00' BETWEEN shop.open_time AND shop.close_time
        )
        OR (shop.open_time > shop.close_time -- exp: 17:00 - 02:00
            AND (
                '18:00:00' BETWEEN shop.open_time AND '23:59:59'
                OR '18:00:00' BETWEEN '00:00:00' AND shop.close_time
            )
        )
    )
16
15
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
15