sql中当关联查询主表很大影响查询速度时怎么办?
sql中当关联查询主表很大时,直接关联,查询速度会较慢,这时可以先利用子查询经筛选条件筛除一部数据,这样主连接表体量减少,这样能一定程度加快速度。
(1)常规join -- 最慢7.558s
select
A.commodity_id,
B.commodity_name,
B.bar_code,
sum(A.sell_quantity) as sellAmount,
sum(A.sell_amount) as sellingPrice,
sum(A.sell_amount)-sum(A.profit) as purchasePrice,
sum(A.profit) as profit,
sum(A.profit)/sum(A.sell_amount)*100 as profitRate
from t_commodity_daily_sales A
join t_commodity B on A.commodity_id = B.commodity_id
where A.shop_id in (select son_shop_id from t_shop_ship where main_shop_id = 133 and son_shop_id != main_shop_id)
and A.create_time >= 1564588800000 and A.create_time < 1572364800000
group by A.commodity_id
order by A.commodity_id
(2)子查询作为join表 -- 其次6.446s
select
A.commodity_id,
A.commodity_name,
A.bar_code,
sum(B.sell_quantity) as sellAmount,
sum(B.sell_amount) as sellingPrice,
sum(B.sell_amount)-sum(B.profit) as purchasePrice,
sum(B.profit) as profit,
sum(B.profit)/sum(B.sell_amount)*100 as profitRate
from t_commodity A
join
(
select commodity_id,sell_quantity,sell_amount,profit
from t_commodity_daily_sales
where shop_id in(select son_shop_id from t_shop_ship where main_shop_id = 133 and son_shop_id != main_shop_id)
and create_time >= 1564588800000 and create_time < 1572364800000
)B on A.commodity_id = B.commodity_id
group by A.commodity_id
order by A.commodity_id
(3)子查询作为连接主表 -- 最快6.402s
select
A.commodity_id,
B.commodity_name,
B.bar_code,
sum(A.sell_quantity) as sellAmount,
sum(A.sell_amount) as sellingPrice,
sum(A.sell_amount)-sum(A.profit) as purchasePrice,
sum(A.profit) as profit,
sum(A.profit)/sum(A.sell_amount)*100 as profitRate
from (
select commodity_id,sell_quantity,sell_amount,profit
from t_commodity_daily_sales
where shop_id in (select son_shop_id from t_shop_ship where main_shop_id = 133 and son_shop_id != main_shop_id)
and create_time >= 1564588800000 and create_time < 1572364800000
)A
join t_commodity B on A.commodity_id = B.commodity_id
group by A.commodity_id
order by A.commodity_id
God will send the rain when you are ready.You need to prepare your field to receive it.