对于“患者”表中的1000名患者,什么是优化此查询的最佳方法:

SELECT patientid,firstname,lastname,mobilephone,email,
       Format(Coalesce((SELECT Sum(ammount) - Sum(( ammount * ( discount / 100 )))
FROM   invoice
WHERE  invoice.patientid = patient.patientid
       AND invoicednumber > 0) - (SELECT Sum(ammount) FROM payment WHERE payment.patientid = patient.patientid), 0), 0) AS answer,
       Date_format((SELECT Max(paymentdate) FROM payment WHERE  payment.patientid = patient.patientid), '%d-%m-%Y')
       AS
       lastpaymentdate
FROM   patient
WHERE  1


[Patient Table][1]
[Invoice Table][2]
[Payment Table][3]
[Result Data][4]


  [1]: https://i.stack.imgur.com/rtCnm.png
  [2]: https://i.stack.imgur.com/czWKk.png
  [3]: https://i.stack.imgur.com/DRJnQ.png
  [4]: https://i.stack.imgur.com/XakbX.png

亚马逊ec2 t2.micro需要10秒
This is the sql fiddle example

最佳答案

在任何RDBM系统中,性能不佳都是由于设计不当造成的。在SQL Fiddle中,您将在varchar字段中保存数字。您当前的表引擎是MyISAM,它不支持关系!?No relationships => no index => no quick lookups
为了提高性能,我建议您改变您的桌子设计。
发票表可能有以下更改。Change Engine to InnoDB

ALTER TABLE `invoice` ENGINE = Innodb;

ALTER TABLE `invoice`
CHANGE COLUMN `patientid` `patientid` INT(12) UNSIGNED NOT NULL ,
CHANGE COLUMN `ammount` `ammount` DECIMAL(14,2) NOT NULL ,
CHANGE COLUMN `discount` `discount` DECIMAL(3,2) NULL DEFAULT '0' ,
ADD INDEX `fk_invoice_patient_idx` (`patientid` ASC);
ALTER TABLE `invoice`
ADD CONSTRAINT `fk_invoice_patient`
  FOREIGN KEY (`patientid`)
  REFERENCES `test`.`patient` (`patientid`)
  ON DELETE RESTRICT
  ON UPDATE CASCADE;

这立即改善了病人和发票表之间的任何查找。对付款表进行相同的更改,然后比较结果。
在上述更改之后,您可以为付款和发票或子查询创建视图,与前面提到的其他视图一样,以加快速度。

关于mysql - 针对患者表中的1000位患者优化此查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54766864/

10-11 03:33