3

有没有更好的方法来执行这个查询而不使用嵌套子查询?

-- 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
);

骑师可以属于多个地区。骑师可以参加多个比赛。

4

3 回答 3

3

它可能效率不高(因为产品会更大),但你可以做到。检查两者的解释。

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
于 2012-09-12T21:46:04.407 回答
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
于 2012-09-12T22:00:40.207 回答
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
于 2012-09-12T21:55:51.440 回答