优化PostgreSQL选择查询(SQLFIDLE)

优化PostgreSQL选择查询(SQLFIDLE),sql,postgresql,query-optimization,sqlfiddle,Sql,Postgresql,Query Optimization,Sqlfiddle,我有两个名为player和team的表,它们通过名为player\u team的第三个表以多对多关系绑定在一起 可以找到表结构和当前查询: 我需要一个查询,返回球员的数据,以及team.id,其中包括球员的最高评级。此外,如果评级为,您可以尝试以下查询: with all_comb as ( select p.id as PLID, t.id as TID, t.rating as RATING from player p, team t,

我有两个名为
player
team
的表,它们通过名为
player\u team
的第三个表以多对多关系绑定在一起

可以找到表结构和当前查询:


我需要一个查询,返回球员的数据,以及
team.id
,其中包括球员的最高评级。此外,如果评级为
,您可以尝试以下查询:

with all_comb as (
select p.id as PLID,
       t.id as TID,
       t.rating as RATING
  from player p,
       team t,
       player_team pt
 where p.id = pt.pid
   and t.id = pt.tid
   and t.rating >0)

select distinct
       a.PLID,
       a.TID,
       a.RATING
  from all_comb a
 where a.RATING = (
       select max(b.RATING)
         from all_comb b
        where a.PLID = b.PLID)
 order by PLID;
小提琴是