我想弄清楚为什么我的MySQL查询需要一分钟才能运行。我无法弄清楚我是否低效地编程某些东西,或者我是否应该预期像这样的滞后时间。以下是代码。MySQL查询的影响
请记住,在我搜索的大部分表格(货件,shipment_financials,shipment_consignees,shipment_shippers)中,有10,000到30,000条记录。
下面是代码:
SELECT users.*, COUNT(DISTINCT shipments.shipment_id) as COUNT_SHIPMENTS, COUNT(DISTINCT clients.client_id) as COUNT_CLIENTS, SUM(shipment_financials.shipment_financial_revenue) as SUM_USER_REVENUE, SUM(shipment_financials.shipment_financial_cost) as SUM_USER_COST FROM users JOIN shipments ON shipments.shipment_details_sales_rep = users.user_id LEFT JOIN shipment_financials ON shipment_financials.shipment_financial_shipment_id = shipments.shipment_id JOIN clients ON clients.client_id = shipments.shipment_details_client JOIN shipment_consignees ON shipment_consignees.shipment_consignee_shipment_id = shipments.shipment_id JOIN shipment_shippers ON shipment_shippers.shipment_shipper_shipment_id = shipments.shipment_id WHERE shipment_consignees.shipment_consignee_id = ( SELECT MAX(shipment_consignees.shipment_consignee_id) FROM shipment_consignees WHERE shipments.shipment_id = shipment_consignees.shipment_consignee_shipment_id ) AND shipment_shippers.shipment_shipper_id = ( SELECT MIN(shipment_shippers.shipment_shipper_id) FROM shipment_shippers WHERE shipments.shipment_id = shipment_shippers.shipment_shipper_shipment_id ) AND users.user_account_id = $account_id AND shipments.shipment_voided = 0 GROUP BY users.user_id ORDER BY SUM_USER_REVENUE desc
因为不是快速奔跑:大量的记录,5连接,多个相关子查询。 –
'解释'它,并做一些优化。 – Blank
你使用索引吗?它会大大提高性能 – andrew