具有多个BETWEEN的MySQL查询始终为NULL

时间:2015-11-30 18:50:31

标签: mysql between

也许我错过了这里显而易见的,但为什么这个查询总是为空?

SELECT ROUND(AVG(`viewer_count`),0) AS avg_viewer FROM `table` 
WHERE 
(id BETWEEN 1 AND 8) 
AND 
(id BETWEEN 26 AND 32)

是否有可能获得这样的多个范围的平均值?

2 个答案:

答案 0 :(得分:2)

由于id不可能介于1和8之间,同时介于26和32之间,因此查询返回NULL,因为没有匹配的行。如果您使用OR作为评论中建议的squemeamish,您将获得两个范围内的平均值。

答案 1 :(得分:1)

SELECT ROUND(AVG(CASE WHEN id BETWEEN 1 AND 8   THEN `viewer_count` END),0) AS avg_viewer1_8
     , ROUND(AVG(CASE WHEN id BETWEEN 26 AND 32 THEN `viewer_count` END),0) AS avg_viewer26_32
FROM `table`