#postgresql
Вопрос:
Когда я выполняю этот простой запрос выбора, ответ возвращается через 30 мс.
select u.id, cv.id
from units u
left join volumes v on v.value = u.value
left join carrier_units cu on cu.id = u.mccus_inspection_id
left join carriers c on c.id = cu.carrier_id
left join carrier_volumes cv on cv.vehicle_id = v.id and cv.carrier_id = c.id
where u.carrier_vehicle_id is null
and cv.id is not null
and u.id = 115215784
and cv.date = cu.date
Однако, когда я пытаюсь выполнить обновление с использованием идентичного шаблона, это занимает 120 секунд или более.
UPDATE units
SET carrier_vehicle_id = cv.id
from units u
left join volumes v on v.value = u.value
left join carrier_units cu on cu.id = u.mccus_inspection_id
left join carriers c on c.id = cu.carrier_id
left join carrier_volumes cv on cv.vehicle_id = v.id and cv.carrier_id = c.id
where u.carrier_vehicle_id is null
and cv.id is not null
and u.id = 115215784
and cv.date = cu.date
Как повысить производительность инструкции Update, чтобы она больше соответствовала запросу Select?
Комментарии:
1. насколько велика таблица и какой индекс у вас есть
carrier_vehicle_id
?
Ответ №1:
Проблема в том, что вы UPDATE
соединяетесь units
с самим собой без условия соединения. Ваши внешние соединения на самом деле являются внутренними соединениями, поэтому вам следует переписать UPDATE
как
UPDATE units u
SET carrier_vehicle_id = cv.id
from volumes v
cross join carrier_units cu
join carriers c on c.id = cu.carrier_id
join carrier_volumes cv on cv.vehicle_id = v.id and cv.carrier_id = c.id
where v.value = u.value
and cu.id = u.mccus_inspection_id
and u.carrier_vehicle_id is null
and cv.id is not null
and u.id = 115215784
and cv.date = cu.date;
Комментарии:
1. Отлично. Спасибо вам за ответ и помощь!