第 1 步:将当前列拆分为两个单独的列(例如open
和close
)。
第2步:SELECT * FROM shops WHERE HOUR(NOW()) BETWEEN open AND close;
或者,您可以即时拆分列:
SELECT * FROM shops
WHERE HOUR(NOW()) BETWEEN
SUBSTRING_INDEX(openclose, '-', 1) AND
SUBSTRING_INDEX(openclose, '-', -1);
但实际上,拆分列,上述查询无法使用列上的任何索引。
考虑到商店每天的营业时间不同的情况。
CREATE TABLE opening_times (
store_id INT NOT NULL,
day_of_week INT NOT NULL, -- 1 = Sunday
open TIME NOT NULL,
close TIME NOT NULL,
PRIMARY KEY (store_id),
FOREIGN KEY (store_id) REFERENCES store(id),
INDEX (day_of_week, open, close) -- suggested index
);
SELECT store.* FROM opening_times
JOIN store ON store.id = opening_times.store_id
WHERE
DAYOFWEEK(NOW()) = day_of_week
AND HOUR(NOW()) BETWEEN open AND close