我想弄清楚为什么我的 MySQL 查询需要一分钟多的时间才能运行。我不知道我是否正在低效地编程,或者我是否应该期待这样的滞后时间。下面是代码。
请记住,在我搜索的大部分表格(shipments、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
最佳答案
主要是 where 语句中的内联查询也减慢了查询的处理速度。但如果这是不可避免的,并且您必须使用内联查询,那么您可以通过执行“LEFT OUTER JOIN”来减少“JOIN”的输出。
“users.*”也从表中获取全部记录,因此减慢了速度,但连接仍然是这里减慢查询速度的主要问题。
关于php - MySQL 查询的影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37803618/