We have 5 tables and we are trying to create a view to get the results.
Below is the view which is working fine.
I need suggestions. Is it a good practice to write this query in this way or it can be optimized in a better way.
SELECT p.Pid, hc.hcid, hc.Accomodation, ghc.ghcid, ghc.ProductFeatures, wp.existing, wp.acute, mc.cardiaccover, mc.cardiaclimitationperiod
FROM TableA p
LEFT JOIN TableB hc
ON p.pid = hc.pid
LEFT JOIN TableC ghc
ON p.pid = ghc.pid
LEFT JOIN (SELECT *
FROM (SELECT hcid,
title,
wperiodvalue + '-' + CASE WHEN
wperiodvalue > 1 THEN
unit +
's' ELSE
unit END wperiod
FROM TableD) d
PIVOT ( Max(wperiod)
FOR title IN (acute,
existing
) ) piv1) wp
ON hc.hcid = wp.hcid
LEFT JOIN (SELECT *
FROM (SELECT hcid,
title + col new_col,
value
FROM TableE
CROSS apply ( VALUES (cover,
'Cover'),
(Cast(limitationperiod AS
VARCHAR
(10)),
'LimitationPeriod') ) x (value, col
)) d
PIVOT ( Max(value)
FOR new_col IN (cardiaccover,
cardiaclimitationperiod,
cataracteyelenscover,
cataracteyelenslimitationperiod
) ) piv2) mc
ON hc.hcid = mc.hcid
Any suggestions would be appreciated.
Thanks
The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:
ALTER TABLE `TableB` ADD INDEX `tableb_idx_pid` (`pid`);
ALTER TABLE `TableC` ADD INDEX `tablec_idx_pid` (`pid`);
ALTER TABLE `es_temp1` ADD INDEX `es_temp1_idx_hcid` (`hcid`);
ALTER TABLE `es_temp2` ADD INDEX `es_temp2_idx_hcid` (`hcid`);
SELECT
p.Pid,
hc.hcid,
hc.Accomodation,
ghc.ghcid,
ghc.ProductFeatures,
wp.existing,
wp.acute,
mc.cardiaccover,
mc.cardiaclimitationperiod
FROM
TableA p
LEFT JOIN
TableB hc
ON p.pid = hc.pid
LEFT JOIN
TableC ghc
ON p.pid = ghc.pid
LEFT JOIN
es_temp1 wp
ON hc.hcid = wp.hcid
LEFT JOIN
es_temp2 mc
ON hc.hcid = mc.hcid