Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding a nested subquery containing a group by

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.

like image 230
jgrowl Avatar asked Jul 02 '26 06:07

jgrowl


1 Answers

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
like image 72
Alain Collins Avatar answered Jul 04 '26 19:07

Alain Collins



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!