我有一个用来记录库存量的大表,它已经是你创建的时候的订单了。
现在,我想得到每家商店所有产品的最新库存量。
代码:
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
但这很慢。
所以我想知道如何使我的查询更有效率。
附言:是吗 SQ.store_product_quantity_new
过得去 max(SQ.time_create)
? 我不确定,只是想 store_product_quantity_new
具有 max(SQ.time_create)
结构
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);
1条答案
按热度按时间j2cgzkjk1#
不能只对一列使用max(),然后自动从同一行中选择其他列。在mysql的更高版本中,默认情况下启用了only\ full\ group\ by选项,这意味着即使尝试此查询也是错误的(请参阅https://dev.mysql.com/doc/refman/5.6/en/group-by-handling.html).
您需要确定哪些行是您想要的,然后选择它们:
SELECT sq.store_id, sq.product_id, sq.time_create AS last_time, sq.store_product_quantity_new FROM stockquantitylogs AS sq INNER JOIN ( SELECT store_id, product_id, MAX(time_create) AS time_create FROM stockquantitylogs GROUP BY store_id, product_id ) AS sq_latest USING(store_id, product_id, time_create)
在这里,我们首先选择所需的(最新的)行:SELECT store_id, product_id, MAX(time_create) AS time_create FROM stockquantitylogs GROUP BY store_id, product_id
然后外部查询通过连接到内部结果中的匹配行来选择要返回的行。要使其正常运行,需要在相关行上建立索引:
INDEX
store_id_product_id_time_create(
store_id,
product_id,
time_create)
请注意,我已经删除了where语句-如果需要,请将其添加到内部sq_latest
查询。