mysql - 过滤与 SQL 中的过滤条件相对应的重复记录和出现次数
问题描述
有一个表并使用键对记录进行分组:stu_class|stu_birth|stu_major。如果有重复记录,则选择 stu_id 最小的记录。所以,我需要计算满足这个条件的记录总数。
例子:
这里, stu_id (100,101) 是基于键的重复记录。但我只想选择最小的 stu_id 记录。它是 stu_id , 100。类似地, stu_id (102,104) 是重复记录。但需要选择 stu_id 102。
然后选择的记录计数应该是 2。我怎样才能使用 SQL 获得这个计数?。我的意思是如何将计算出的记录总数设为 2。
解决方案
一种方法使用窗口函数:
select t.*
from (select t.*,
row_number() over (partition by stu_class, stu_birth, stu_major order by stu_id) as seqnum
from t
) t
where seqnum = 1;
从版本 8 开始,这在 MySQL 中可用。
一种替代方法使用相关子查询,并且可能更快,即使在版本 8 中也是如此:
select t.*
from t
where t.stu_id = (select min(t2.stu_id)
from t t2
where t2.stu_class = t.stu_class and t2.stu_birth = t.stu_birth and t2.stu_major = t.stu_major
);
这可以利用上的索引(stu_class, stu_birth, stu_major, stu_id)
。
编辑
如果您只想要总记录,请使用聚合:
select stu_class, stu_birth, stu_major, min(stu_id), count(*) as cnt
from t
group by stu_class, stu_birth, stu_major;
推荐阅读
- php - 在主题类中找不到 PhpStorm 方法
- spring-boot - 使用 Flyway 和 Spring Boot 迁移基线
- python - Python:CSV 编写器非常慢,需要建议以加快速度
- angular - “Promise”类型上不存在属性“管道”
- matlab - Matlab图中的垂直线未显示:缩放问题
- php - 颠倒PHP数组值?
- c - 函数内联使用更多 RAM 还是 ROM?对微控制器的 RAM 有什么影响?
- spring - 如何在 Spring Boot 2.1.0 中登录时禁用 Set-Cookie 标头上的 HttpOnly 标志
- ios - 谁负责使用协调器设计模式调用服务
- android - 向 FCM 服务器发送推送通知不起作用