26/11/2024 | jiangws 你的查询目标是从 shipment 表中获取与 distance 表关联的数据,并筛选出里程数超过 3000 的记录,同时按 shipment_id 排序。这是一个典型的查询场景,可以通过以下方式改进性能或提高可读性: 原查询 SELECT *FROM shipmentLEFT JOIN distanceON (shipment.origin = distance.origin)AND (shipment.destination = distance.destination)WHERE distance.miles > 3000ORDER BY shipment_id; 方法 1:使用 INNER JOIN SELECT shipment.*, distance.milesFROM shipmentINNER JOIN distanceON shipment.origin = distance.originAND shipment.destination = distance.destinationWHERE distance.miles > 3000ORDER BY shipment.shipment_id; 适用场景: 数据量适中,无需提前过滤 distance 表。 只需简单的等值连接即可满足需求。 方法 2:将筛选条件提前(推荐) SELECT shipment.shipment_id, shipment.ship_no, filtered_distance.milesFROM shipmentINNER JOIN (SELECT origin, destination, milesFROM distanceWHERE miles > 3000) AS filtered_distanceON shipment.origin = filtered_distance.originAND shipment.destination = filtered_distance.destinationORDER BY shipment.shipment_id; 改进点: 子查询用别名 filtered_distance 表示。 主查询中使用 filtered_distance.miles 代替 distance.miles。 提前过滤 distance.miles > 3000,减少主查询的处理范围。 方法 3:减少 SELECT * 的使用 SELECT shipment.shipment_id, shipment.ship_no, filtered_distance.milesFROM shipmentINNER JOIN (SELECT origin, destination, milesFROM distanceWHERE miles > 3000) AS filtered_distanceON shipment.origin = filtered_distance.originAND shipment.destination = filtered_distance.destinationORDER BY shipment.shipment_id; 适用场景: 如果只需要特定字段,避免使用 SELECT * 提高效率。 方法 4:完全索引优化(附加建议) 如果你的查询性能依赖大表,可以添加索引来进一步优化查询速度: distance 表复合索引: CREATE INDEX idx_distance_origin_destination_milesON distance (origin, destination, miles); shipment 表单字段或复合索引: CREATE INDEX idx_shipment_origin_destinationON shipment (origin, destination); 最终推荐的查询 SELECT shipment.shipment_id, shipment.ship_no, filtered_distance.milesFROM shipmentINNER JOIN (SELECT origin, destination, milesFROM distanceWHERE miles > 3000) AS filtered_distanceON shipment.origin = filtered_distance.originAND shipment.destination = filtered_distance.destinationORDER BY shipment.shipment_id; 这样改写后: 确保字段引用正确。 逻辑清晰,易于维护。 索引优化提升大表查询性能。 希望对你有所帮助!如果有进一步问题,随时提问!