In MySQL, I have a simple join between 2 tables. Something like
select a.id, SUM(b.qty) from a inner join b on a.id=b.id
where a.id=12345
group by a.id
It runs normal as a query. But when I keep the query
select a.id, SUM(b.qty) from a inner join b on a.id=b.id
group by a.id
in a view called view_ab
, the view takes enormous amount of time when i run the following query on the view.
select * from view_ab where id = 12345
Both these tables are large tables. Unable to figure out the reason for such a drop in performance. Please help resolve this performance issue
EDIT: This is the view SQL
CREATE VIEW view_ab AS SELECT
r.drid AS drid,
SUM(s.return_qty) AS return_qty
FROM tbl_deliveryroute r INNER JOIN tbl_deliveryroute_sku s ON r.drid =
s.drid GROUP BY r.drid;
This is the query
SELECT
r.drid AS drid,
SUM(s.return_qty) AS return_qty
FROM tbl_deliveryroute r INNER JOIN tbl_deliveryroute_sku s ON r.drid =
s.drid WHERE r.drid=12718651
GROUP BY r.drid;
This is the query on the VIEW
SELECT * FROM view_ab WHERE drid=12718651;
Execution plan of the view
EXPLAIN EXTENDED SELECT * FROM view_ab WHERE drid=12718651;
id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 PRIMARY (NULL) ref 4 const 10 100.00 (NULL)
2 DERIVED s (NULL) ALL idx_tbl_deliverroute_sku_drid (NULL) (NULL) (NULL) 15060913 100.00 USING TEMPORARY; USING filesort
2 DERIVED r (NULL) eq_ref PRIMARY,FK_tbl_deliveryroute_1 PRIMARY 4 humdemotest.s.drid 1 100.00 USING INDEX
EXPLAIN EXTENDED SELECT
r.drid AS drid,
SUM(s.return_qty) AS return_qty
FROM tbl_deliveryroute r INNER JOIN tbl_deliveryroute_sku s ON r.drid =
s.drid WHERE r.drid=12718651
GROUP BY r.drid;
id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 SIMPLE r (NULL) const PRIMARY PRIMARY 4 const 1 100.00 USING INDEX
1 SIMPLE s (NULL) ref idx_tbl_deliverroute_sku_drid idx_tbl_deliverroute_sku_drid 4 const 22 100.00 (NULL)
EXPLAIN
to each of them. Note that for the former MySQL may be doing filtering first then grouping, and for the latter vice-versa which kind of explains the issue. (If this is the case, you could stick to a stored procedure instead.) – minmaxavgEXPLAIN EXTENDED
result of the query (possibly censoring sensitive information) would be helpful. Also, it might be worth checking if both schemas for staging and production environment are identical, especially the KEY / INDEX part. – minmaxavg