需要在左联接下优化此视图查询

时间:2018-10-23 05:21:37

标签: mysql

DROP VIEW IF EXISTS `view_pendinginvoices`$$

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `view_pendinginvoices` AS 
SELECT
  `p`.`mrno`             AS `MRNO`,
  CONCAT(`p`.`patientname`) AS `PATIENTNAME`,
  `v`.`patient_visit_id` AS `visitno`,
  SUM(`pb`.`amount`)     AS `amount`,
  `p`.`patient_id`       AS `patient_id`,
  `v`.`visit_date`       AS `visit_date`,
  `v`.`visittype`        AS `visittype`,
  `v`.`site_id`          AS `site_id`,
  `v`.`visitid`          AS `visitid`
FROM (((`patient` `p`
LEFT JOIN `prefix_master` `pm`
   ON ((`pm`.`id` = `p`.`patprefix`)))
JOIN `view_pendinginvoices_sub` `pb`
   ON ((`p`.`patient_id` = `pb`.`PATIENTID`)))
JOIN `visit` `v`
   ON ((`v`.`visitid` = `pb`.`VISIT_ID`)))
GROUP BY `p`.`mrno`,`pm`.`prefix`,`p`.`patientname`,`v`.`patient_visit_id`,`p`.`patient_id`,`v`.`visit_date`,`v`.`visittype`,`v`.`site_id`,`v`.`visitid`
;$$
DELIMITER ;

1 个答案:

答案 0 :(得分:0)

查看您的代码似乎很多()都没有用,并且连用了单个值

DROP VIEW IF EXISTS `view_pendinginvoices`$$

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER 
    VIEW `view_pendinginvoices` AS 
SELECT
  `p`.`mrno`             AS `MRNO`,
  `p`.`patientname`      AS `PATIENTNAME`,
  `v`.`patient_visit_id` AS `visitno`,
  SUM(`pb`.`amount`)     AS `amount`,
  `p`.`patient_id`       AS `patient_id`,
  `v`.`visit_date`       AS `visit_date`,
  `v`.`visittype`        AS `visittype`,
  `v`.`site_id`          AS `site_id`,
  `v`.`visitid`          AS `visitid`
FROM `patient` `p`
    LEFT JOIN `prefix_master` `pm` ON `pm`.`id` = `p`.`patprefix`
    JOIN `view_pendinginvoices_sub` `pb` ON `p`.`patient_id` = `pb`.`PATIENTID`
    JOIN `visit` `v` ON `v`.`visitid` = `pb`.`VISIT_ID`
GROUP BY `p`.`mrno`
        ,`pm`.`prefix`
        ,`p`.`patientname`
        ,`v`.`patient_visit_id`
        ,`p`.`patient_id`
        ,`v`.`visit_date`
        ,`v`.`visittype`
        ,`v`.`site_id`
        ,`v`.`visitid`
;$$

DELIMITER ;

如果需要提高性能,请确保在连接所涉及的列上具有正确的索引

create index  idx1  on patient (patient_id, patprefix )