【发布时间】:2016-10-14 16:34:20
【问题描述】:
我试图弄清楚为什么我的 MySQL 查询需要一分钟多的时间才能运行。我不知道我是否在编程效率低下,或者我是否应该期待这样的滞后时间。下面是代码。
请记住,在我搜索的大多数表(shipments、shipping_financials、shipping_consignees、shipping_shippers)中都有 10,000 到 30,000 条记录。
代码如下:
选择用户。*,COUNT(DISTINCT shippings.shipment_id) 作为 COUNT_SHIPMENTS,COUNT(DISTINCT clients.client_id) 作为 COUNT_CLIENTS,SUM(shipment_financials.shipment_financial_revenue) 作为 SUM_USER_REVENUE,SUM(shipment_financials.shipment_financial_cost) 作为 SUM_USER_COST 来自用户 在 shipping.shipment_details_sales_rep = users.user_id 上加入货件 左加入 shipping_financials ON shipping_financials.shipment_financial_shipment_id = shipping.shipment_id 在 clients.client_id = shipping.shipment_details_client 上加入客户 加入 shipping_consignees ON shipping_consignees.shipment_consignee_shipment_id = shipping.shipment_id 加入 shipping_shippers ON shipping_shippers.shipment_shipper_shipment_id = shipping.shipment_id WHERE shipping_consignees.shipment_consignee_id = ( 选择最大(shipment_consignees.shipment_consignee_id) FROM shipping_consignees WHERE shipping.shipment_id = shipping_consignees.shipment_consignee_shipment_id ) AND shipping_shippers.shipment_shipper_id = ( 选择最小值(shipment_shippers.shipment_shipper_id) FROM shipping_shippers WHERE shipping.shipment_id = shipping_shippers.shipment_shipper_shipment_id ) AND users.user_account_id = $account_id AND shipping.shipment_voided = 0 GROUP BY users.user_id ORDER BY SUM_USER_REVENUE desc【问题讨论】:
-
运行不快,因为:大量记录、5 个连接、多个相关子查询。
-
EXPLAIN它,做一些优化。 -
你使用索引吗?它将大大提高性能
-
@andrew - 你能解释一下索引是什么意思吗?
-
@BradH 在这里阅读:dev.mysql.com/doc/refman/5.7/en/mysql-indexes.html