我想弄清楚爲什麼我的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