我需要一些简化查询的帮助(比如避免重复等)
http://www.sqlfiddle.com/#!17/3607d/1/0
我们有 2 个对象:
working hours
定义:mon_from
,mon_to
,tue_from
...; 如果值null
在那一天不起作用office
用name
它timezone
定义working_hours_id
需要简化查询该办公室是否正在工作,如果办公室没有指定工作时间,那么它是 24/7 开放的。
SELECT
name,
(CURRENT_TIMESTAMP::time AT TIME ZONE timezone)::time,
(workinghours.id IS NULL) OR ((
((CURRENT_TIMESTAMP::time AT TIME ZONE timezone)::time BETWEEN mon_from AND mon_to
AND EXTRACT(isodow FROM CURRENT_TIMESTAMP AT TIME ZONE timezone) = 1) OR
((CURRENT_TIMESTAMP::time AT TIME ZONE timezone)::time BETWEEN tue_from AND tue_to
AND EXTRACT(isodow FROM CURRENT_TIMESTAMP AT TIME ZONE timezone) = 2) OR
((CURRENT_TIMESTAMP::time AT TIME ZONE timezone)::time BETWEEN wed_from AND wed_to
AND EXTRACT(isodow FROM CURRENT_TIMESTAMP AT TIME ZONE timezone) = 3) OR
((CURRENT_TIMESTAMP::time AT TIME ZONE timezone)::time BETWEEN thu_from AND thu_to
AND EXTRACT(isodow FROM CURRENT_TIMESTAMP AT TIME ZONE timezone) = 4) OR
((CURRENT_TIMESTAMP::time AT TIME ZONE timezone)::time BETWEEN fri_from AND fri_to
AND EXTRACT(isodow FROM CURRENT_TIMESTAMP AT TIME ZONE timezone) = 5) OR
((CURRENT_TIMESTAMP::time AT TIME ZONE timezone)::time BETWEEN sat_from AND sat_to
AND EXTRACT(isodow FROM CURRENT_TIMESTAMP AT TIME ZONE timezone) = 6) OR
((CURRENT_TIMESTAMP::time AT TIME ZONE timezone)::time BETWEEN sun_from AND sun_to
AND EXTRACT(isodow FROM CURRENT_TIMESTAMP AT TIME ZONE timezone) = 7)
) IS True) AS in_workinghours
FROM office
LEFT JOIN workinghours ON (workinghours.id = office.workinghours_id)