首页 > 解决方案 > 在大型数据库中使用 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

谢谢

标签: mysqldatabase

解决方案


尝试这个 。

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

希望这会有所帮助


推荐阅读