我有一个包含重复表达式的查询。可以写得更紧凑吗?
select id from `vacature_saved_searches`
where `saved_search_interval` = 1 and
DAYOFWEEK(CURDATE()) BETWEEN 2 AND 6 and
`last_processing_started_datetime` < CURDATE() - INTERVAL 1 HOUR
UNION
select id from `vacature_saved_searches`
where `saved_search_interval` = 2 and
DAYOFWEEK(CURDATE()) IN (2, 4, 6) and
`last_processing_started_datetime` < CURDATE() - INTERVAL 1 HOUR
UNION
select id from `vacature_saved_searches`
where `saved_search_interval` = 3 and
DAYOFWEEK(CURDATE()) = 3 AND
`last_processing_started_datetime` < CURDATE() - INTERVAL 1 HOUR
UNION
select id from `vacature_saved_searches`
where `saved_search_interval` = 4 and
DAYOFWEEK(CURDATE()) = 3 and
DAYOFMONTH(CURDATE()) BETWEEN 1 AND 7 and
`last_processing_started_datetime` < CURDATE() - INTERVAL 1 HOUR;
答案 0 :(得分:1)
没那么好。此外,对于这个确切的查询结果应该是相同的,但如果4个查询之间存在重叠,您将在原始UNION中获得重复。
select id
from `vacature_saved_searches`
where `last_processing_started_datetime` < CURDATE() - INTERVAL 1 HOUR AND
((`saved_search_interval` = 1 and DAYOFWEEK(CURDATE()) BETWEEN 2 AND 6) OR
(`saved_search_interval` = 2 and DAYOFWEEK(CURDATE()) IN (2, 4, 6)) OR
(`saved_search_interval` = 3 and DAYOFWEEK(CURDATE()) = 3) OR
(`saved_search_interval` = 4 and DAYOFWEEK(CURDATE()) = 3 and DAYOFMONTH(CURDATE()) BETWEEN 1 AND 7))
答案 1 :(得分:1)
不确定。为什么联合它的同一张桌子?
为什么不
select id from `vacature_saved_searches`
where
((`saved_search_interval` = 1 and
DAYOFWEEK(CURDATE()) BETWEEN 2 AND 6)
or
(`saved_search_interval` = 2 and
DAYOFWEEK(CURDATE()) IN (2, 4, 6))
or
(`saved_search_interval` = 3 and
DAYOFWEEK(CURDATE()) = 3)
or
(`saved_search_interval` = 4 and
DAYOFWEEK(CURDATE()) = 3 and
DAYOFMONTH(CURDATE()) BETWEEN 1 AND 7))
and `last_processing_started_datetime` < CURDATE() - INTERVAL 1 HOUR;
答案 2 :(得分:1)
您可以结合使用DISTINCT和重新构造查询来使用OR子句而不是联合:
select DISTINCT id from `vacature_saved_searches`
where ((`saved_search_interval` = 1 and DAYOFWEEK(CURDATE()) BETWEEN 2 AND 6) OR
(`saved_search_interval` = 2 and DAYOFWEEK(CURDATE()) IN (2, 4, 6)) OR
(`saved_search_interval` = 3 and DAYOFWEEK(CURDATE()) = 3) OR
(`saved_search_interval` = 4 and DAYOFWEEK(CURDATE()) = 3 and
DAYOFMONTH(CURDATE()) BETWEEN 1 AND 7))
AND `last_processing_started_datetime` < CURDATE() - INTERVAL 1 HOUR;