0

我有 2 个名为playerand的表team,它们通过名为 的第三个表以多对多关系联系在一起player_team

可以找到表结构和当前查询:http ://sqlfiddle.com/#!2/e6db4/18

我需要一个查询,它返回玩家的数据以及team.id,其中包括玩家的最高评分。此外,如果评分为<= X,则应排除该玩家。

示例查询返回正确的结果,但效率很低。

显然,只访问每个表的行一次就可以达到相同的结果,但问题是如何实现呢?(我更喜欢使用 PostgreSQL 方言的回复)

4

1 回答 1

0

这是您可以尝试的查询:

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;

sqlfiddle 在这里

于 2014-02-10T16:12:46.587 回答