У меня есть две таблицы:
поездки , с колонками user_id и bike_id
эксперимент_экспозиции , с колонками subject_type и subject_id
subject_type
может быть User
или Bike
, а subject_id
соответствует либо user_id
, либо bike_id
.
Первые два запроса относительно быстрые, они занимают примерно одинаковое время:
select count(*)
from trips
join experiment_exposures e1 on e1.subject_type = 'User' and e1.subject_id = trips.user_id
join experiment_exposures e2 on e2.subject_type = 'Bike' and e2.subject_id = trips.bike_id;
и
select count(*)
from trips
join (select * from experiment_exposures where subject_type = 'User') e1 on e1.subject_id = trips.user_id
join (select * from experiment_exposures where subject_type = 'Bike') e2 on e2.subject_id = trips.bike_id;
Однако этот запрос как минимум в 100 раз медленнее:
select count(*)
from trips
join experiment_exposures e
on (e.subject_type = 'User' and e.subject_id = trips.user_id)
or (e.subject_type = 'Bike' and e.subject_id = trips.bike_id);
Почему такая большая разница? Разве первый и третий запросы не совпадают? Интуитивно понятно, что третий запрос будет быстрее, потому что есть только 1 объединение.