SQL 计数聚合函数和子查询

SQL count aggregate functions and subquery

我只是在学习SQL专门学习聚合函数和子查询

我有一个包含列 c0, c1, c2, c3 的数据库 table。

我的查询:

SELECT ID, count(ID) 
FROM ((select ID from tbl1 where c0 BETWEEN 4 and 7) 
UNION ALL
(select ID from tbl1 where c1 BETWEEN 5 and 7) 
UNION ALL
(select ID from tbl1 where c2 BETWEEN 6 and 10) 
UNION ALL
(select ID from tbl1 where c3 BETWEEN 1 and 5)) AS tbl
GROUP BY ID HAVING count(ID) >= 2

能否重写上面的查询以使结果更快?或者如何使我的查询更快?

我认为您根本不需要聚合。只需计算每一行中的匹配项。

假设id在table中是唯一的:

select id,
       ((c0 between 4 and 7) + (c1 between 5 and 7) + (c2 between 6 and 10) +
        (c3 between 1 and 5)
       ) as cnt
from tbl1
having cnt >= 2;

MySQL 将数字上下文中的布尔值视为数字,1 表示真,0 表示假,因此表达式 c0 between 4 and 7 基本上等同于 case when c0 between 4 and 7 then 1 else 0 end,但更容易编写.

MySQL 还扩展了 having 子句,因此它可以在没有 group by 的情况下工作。在这种情况下,它的行为类似于 where,但您可以使用 select.

中定义的别名

注意:如果列有 NULL 个值,这会稍微复杂一些。

如果id不是唯一的,那么你基本上可以用聚合做同样的事情:

select id,
       sum((c0 between 4 and 7) + (c1 between 5 and 7) + (c2 between 6 and 10) +
           (c3 between 1 and 5)
          ) as cnt
from tbl1
group by id
having cnt >= 2;

但是,名为 id 的列应该是唯一的。