I have a big table which used to record stock quantity, it is already order by time_create.
Now, I want to get latest all products stock quantity in each store.
Code:
select SQ.store_id,SQ.product_id, max(SQ.time_create) as last_time, SQ.store_product_quantity_new
from stockquantitylogs as SQ
where SQ.time_create > unix_timestamp("2018-08-01")*1000
group by SQ.store_id, SQ.product_id
But this is very very slow.
So I wonder how to make my query more efficient.
PS: Does SQ.store_product_quantity_new
get by max(SQ.time_create)
? I am not sure this, just want to get store_product_quantity_new
withmax(SQ.time_create)
Structure
create table stockquantitylogs
(
id char(36) collate utf8_bin default '' not null
primary key,
store_id char(36) collate utf8_bin default '' not null,
product_id char(36) collate utf8_bin default '' not null,
time_create bigint not null,
time_update bigint not null,
store_product_quantity_old int not null,
store_product_quantity_new int not null
);
create index IX_product_id
on stockquantitylogs (product_id);
create index IX_store_id
on stockquantitylogs (store_id);
create index IX_time_create
on stockquantitylogs (time_create);
create index IX_time_update
on stockquantitylogs (time_update);
The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:
ALTER TABLE `stockquantitylogs` ADD INDEX `stockquantitylogs_idx_time_create` (`time_create`);
ALTER TABLE `stockquantitylogs` ADD INDEX `stockquantitylogs_idx_store_id_product_id` (`store_id`,`product_id`);
SELECT
SQ.store_id,
SQ.product_id,
max(SQ.time_create) AS last_time,
SQ.store_product_quantity_new
FROM
stockquantitylogs AS SQ
WHERE
SQ.time_create > unix_timestamp('2018-08-01') * 1000
GROUP BY
SQ.store_id,
SQ.product_id
ORDER BY
NULL