mysql - 在大型数据库中使用 JOIN 进行 MySQL 查询
问题描述
我有一个包含数亿行的 MySQL 表。请参阅下面的创建语句:
CREATE TABLE `transaction_history` (
`transaction_history_id` int(11) NOT NULL AUTO_INCREMENT,
`type_id` int(11) NOT NULL,
`sub_type_id` int(11) DEFAULT NULL,
`transaction_id` int(11) DEFAULT NULL,
`settlement_date_time` datetime DEFAULT NULL,
PRIMARY KEY (`transaction_history_id`),
UNIQUE KEY `transaction_history_id_UNIQUE` (`transaction_history_id`),
KEY `type_id_idx` (`type_id`),
KEY `sub_type_id_idx` (`sub_type_id_id`),
KEY `transaction_id_idx` (`ufmid`),
KEY `settlement_date` (`settlement_date_time`),
KEY `type_sub_type` (`type_id`,`sub_type_id`)
) ENGINE=InnoDB AUTO_INCREMENT=36832823 DEFAULT CHARSET=latin1;
表上信息:每个transaction_id有多个settlement_date_times。type_id 和 sub_type_id 一起是唯一的
我需要创建的查询:对于每个 transaction_id,我需要获取最新的结算日期时间,然后计算(type_id 和 sub_type)的数量。
所以结果看起来像这样:
(type_id,sub_type_id) -> count
(3,4) -> 23500
(2,2) -> 569323
(2,3) -> 45028
(3,2) -> 1038943
无论我做什么,我都无法创建运行相当快的查询。我创建的所有内容都会在 20 分钟后超时。有没有办法在几分钟或几秒钟内运行这个查询?
我尝试的查询之一:
select count(a1.transaction_id), a1.type_id, a1.sub_type_id
from transaction_history a1, transaction_history a2
where a1.transaction_id= a2.transaction_id
and not exists (Select a1.settlement_date_time < a2.settlement_date_time)
group by a1.type_id, a1.sub_type_id
谢谢
解决方案
尝试这个 。
select count(a1.transaction_id), a1.type_id, a1.sub_type_id
from transaction_history a1 join transaction_history a2 using(transaction_id)
where a1.settlement_date_time > a2.settlement_date_time
group by a1.type_id, a1.sub_type_id
希望这会有所帮助
推荐阅读
- android - Android Gradle 6.1.1 问题 - settings.gradle.kts 中的 ScriptCompilationException
- python - 龙卷风/旋风中的长轮询可扩展架构
- java - python中的**和^有什么区别
- c++ - 非静态数据成员初始化器仅适用于 -std=c++11 或 -std=gnu++11
- java - url为空时如何隐藏Imageview
- javascript - 试图将一个警报分成 2 个警报
- go - 使用来自 github 的包时尝试编译 golang 时出错
- amazon-web-services - 在 AWS Lambda 执行处理程序之外缓存异步 API 结果
- python - 仅编码无符号整数时的base64字符串长度计算
- php - datalist country 选择要显示的州