I have two tables, that are Activities and ActivityDetails as below
create table Activities
(
Id char(36) primary key,
BranchId char(36) not null,
ReferenceBranchId char(36) null,
Date datetime not null,
Type varchar(100) not null, -- Production, Delivery, Reception, SalesOrder
Total decimal(16, 2) not null,
Note varchar(400) null,
IsActive bit(1) not null,
CreatedById char(36) not null,
CreatedDate datetime not null,
ModifiedById char(36) null,
ModifiedDate datetime null,
constraint foreign key (BranchId) references Branches(Id) on delete cascade on update cascade,
constraint foreign key (ReferenceBranchId) references Branches(Id) on delete cascade on update cascade,
constraint foreign key (CreatedById) references Users(Id) on delete cascade on update cascade,
constraint foreign key (ModifiedById) references Users(Id)
);
create table ActivityDetails
(
Id char(36) primary key,
ActivityId char(36) not null,
No int not null,
ItemId char(36) not null,
Qty decimal(16,2) not null,
IsActive bit(1) not null,
CreatedById char(36) not null,
CreatedDate datetime not null,
ModifiedById char(36) null,
ModifiedDate datetime null,
constraint foreign key (ActivityId) references Activities(Id) on delete cascade on update cascade,
constraint foreign key (ItemId) references Items(Id) on delete cascade on update cascade,
constraint foreign key (CreatedById) references Users(Id) on delete cascade on update cascade,
constraint foreign key (ModifiedById) references Users(Id)
);
and a query as below
select
Activities.BranchId, Activities.Type, ActivityDetails.ItemId,
sum(ActivityDetails.Qty)
from Activities
join ActivityDetails
on Activities.Id = ActivityDetails.ActivityId and ActivityDetails.IsActive = 1
where Activities.IsActive = 1
group by Activities.BranchId, Activities.Type, ActivityDetails.ItemId;
The query causes timeout on the workbench.
Error Code: 2013. Lost connection to MySQL server during query 600.495 sec
The Activities has ~60.000 rows and the ActivityDetails has ~225.000 rows.
I already tried to add index, but it seems that it has no effect.
alter table Activities add index BranchIdTypeIdx (BranchId, Type);
alter table ActivityDetails add index ItemIdQtyIdx (ItemId, Qty);
The explain of the query is as below
id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra
---|-------------|------------------|-------------|------|---------------|------------|---------|---------------|---------|----------|---------------------------------------------
1 | SIMPLE | Activities | null | ALL | PRIMARY | null | null | null | 58623 | 50.00 | Using where; Using temporary; Using filesort
1 | SIMPLE | ActivityDetails | null | ref | ActivityId | ActivityId | 108 | Activities.Id | 3 | 50.00 | Using where
What do I need to do to optimize the query (at least it doesn't timeout)?