是否有更好的方法可以在不使用嵌套子查询的情况下执行此查询?
-- 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
);
骑师可以属于多个地区。骑师可以参加多场比赛。
答案 0 :(得分:3)
它可能效率不高(因为产品会更大),但你可以做到。检查两者上的EXPLAIN。
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
答案 1 :(得分:2)
你可以这样做,我相信:
select distinct r.id, r.description
from jockeys_races jra
inner join races r on r.id = jra.race_id
inner join jockeys_regions jre on jre.jockey_id=jra.jockey_id
group by r.id, r.description, jre.jockey_id
having count(jre.region) > 1
答案 2 :(得分:1)
您不希望在MySQL中使用IN和子查询。 。 。优化器在这个构造中做得很差。在这种情况下,您可以将子查询移动到FROM子句:
select distinct r.id, r.description
from jockeys_races jra inner join
races r
on r.id = jra.race_id join
(select jre.jockey_id
from jockeys_regions jre
group by jre.jockey_id
having count(*) > 1
) ji
on jra.jockey_id = ji.jockey_id