你的查询目标是从 shipment 表中获取与 distance 表关联的数据,并筛选出里程数超过 3000 的记录,同时按 shipment_id 排序。这是一个典型的查询场景,可以通过以下方式改进性能或提高可读性:


原查询

SELECT *
FROM shipment
LEFT JOIN distance
ON (shipment.origin = distance.origin)
AND (shipment.destination = distance.destination)
WHERE distance.miles > 3000
ORDER BY shipment_id;


方法 1:使用 INNER JOIN

SELECT shipment.*, distance.miles
FROM shipment
INNER JOIN distance
ON shipment.origin = distance.origin
AND shipment.destination = distance.destination
WHERE distance.miles > 3000
ORDER BY shipment.shipment_id;

适用场景:

数据量适中,无需提前过滤 distance 表。

只需简单的等值连接即可满足需求。


方法 2:将筛选条件提前(推荐)

SELECT shipment.shipment_id, shipment.ship_no, filtered_distance.miles
FROM shipment
INNER JOIN (
SELECT origin, destination, miles
FROM distance
WHERE miles > 3000
) AS filtered_distance
ON shipment.origin = filtered_distance.origin
AND shipment.destination = filtered_distance.destination
ORDER 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.miles
FROM shipment
INNER JOIN (
SELECT origin, destination, miles
FROM distance
WHERE miles > 3000
) AS filtered_distance
ON shipment.origin = filtered_distance.origin
AND shipment.destination = filtered_distance.destination
ORDER BY shipment.shipment_id;

适用场景:

如果只需要特定字段,避免使用 SELECT * 提高效率。


方法 4:完全索引优化(附加建议)

如果你的查询性能依赖大表,可以添加索引来进一步优化查询速度:

  1. distance 表复合索引:

CREATE INDEX idx_distance_origin_destination_miles
ON distance (origin, destination, miles);

  1. shipment 表单字段或复合索引:

CREATE INDEX idx_shipment_origin_destination
ON shipment (origin, destination);


最终推荐的查询

SELECT shipment.shipment_id, shipment.ship_no, filtered_distance.miles
FROM shipment
INNER JOIN (
SELECT origin, destination, miles
FROM distance
WHERE miles > 3000
) AS filtered_distance
ON shipment.origin = filtered_distance.origin
AND shipment.destination = filtered_distance.destination
ORDER BY shipment.shipment_id;


这样改写后:

  1. 确保字段引用正确。
  2. 逻辑清晰,易于维护。
  3. 索引优化提升大表查询性能。

希望对你有所帮助!如果有进一步问题,随时提问!