0

我正在寻找优化以下 SQL 查询的方法。我正在使用 MS SQL Server 2008。我在想是否有任何方法可以整合外部连接,它会加快速度……如果有人有任何意见,将不胜感激。谢谢

SELECT employee.employee_id,
   coalesce (room.ship_id, ship.ship_id) AS ship_id,
   SUBSTRING (employee.service_id, 0, 6) AS cost_code,
   employee_station.room_cat AS nws_room_cat
FROM employee
   LEFT OUTER JOIN room
      ON     employee.ship_id = room.ship_id
         AND employee.floor_id = room.floor_id
         AND employee.room_id = room.room_id
   LEFT OUTER JOIN ship
      ON employee.ship_id = ship.ship_id
   LEFT OUTER JOIN employee_station
      ON COALESCE (ship.property_type, '') =
            COALESCE (employee_station.property_type, '')
         AND COALESCE (room.work_center_id, '') = COALESCE (employee_station.work_center_id, '')
         AND COALESCE (employee.pay_plan, '') =
                COALESCE (employee_station.pay_plan, '')
         AND COALESCE (employee.employee_type, '') =
                COALESCE (employee_station.employee_type, '')
         AND COALESCE (SUBSTRING (employee.service_id, 0, 6), '') =
                COALESCE (employee_station.cost_code, '')
   LEFT OUTER JOIN roomtype
      ON room.room_type = roomtype.room_type
   LEFT OUTER JOIN dp
      ON employee.service_id = dp.service_id

注意:为了清楚起见,我故意省略了 SELECT 语句中的许多字段。所以 roomtype 和 dp 表实际上正在被使用......

4

2 回答 2

1

OUTER JOIN 不是问题。问题在于将列包装在函数中。

ON COALESCE (ship.property_type, '') = COALESCE (employee_station.property_type, '')

这种结构会阻止优化器制定有效的查询计划——直到运行时它才知道函数的值是什么,因此如果索引存在,它就无法使用它们。

在没有函数的情况下重写查询,优化器将能够做出更好的决策。

于 2012-12-18T20:43:09.663 回答
0

您可以尝试加入 CHECKSUMS - 根据我的经验,它通常比复杂条件提供更好的性能:

SELECT 
--columns you need
FROM employee
LEFT OUTER JOIN room
ON CHECKSUM(employee.ship_id, employee.floor_id, employee.room_id) 
= CHECKSUM(room.ship_id, room.floor_id, room.room_id)
LEFT OUTER JOIN ship
ON employee.ship_id = ship.ship_id
LEFT OUTER JOIN employee_station
ON CHECKSUM(ship.property_type, room.work_center_id, employee.pay_plan, employee.employee_type, SUBSTRING (employee.service_id, 0, 6)) 
= CHECKSUM(employee_station.property_type, employee_station.work_center_id, employee_station.pay_plan, employee_station.employee_type, employee_station.cost_code)
LEFT OUTER JOIN roomtype
ON room.room_type = roomtype.room_type
LEFT OUTER JOIN dp
ON employee.service_id = dp.service_id
于 2012-12-18T21:17:37.273 回答