Is there a better way to perform this query without using a nested subquery?
-- select all races for jockeys which have multiple regions
select distinct r.id, r.description
from jockeys_races jra inner join races r on r.id = jra.race_id
where jra.jockey_id in (
select jre.jockey_id
from jockeys_regions jre
group by jre.jockey_id
having count(*) > 1
);
Jockeys can belong to multiple regions. Jockeys can be in multiple races.
It may not be as efficient (since the product will be larger), but you can do it. Check the EXPLAIN on both.
select distinct r.id, r.description
from races r
inner join jockey_races jra on r.id = jra.race_id
inner join jockey_regions jre on jra.jockey_id = jre.jockey_id
group by r.id, r.description, jre.jockey_id
having count(*) > 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With