我有 2 个名为 player
和 team
的表,它们通过名为 player_team
的第三个表以多对多关系绑定在一起。
可以找到表结构和当前查询:http://sqlfiddle.com/#!2/e6db4/18
我需要一个查询,它返回玩家的数据以及team.id
,其中包括玩家的最高评分。此外,如果评级为 <= X
,则应排除该玩家。
示例查询返回正确的结果,但效率很低。
显然,仅访问每个表的行一次可以实现相同的结果,但问题是如何实现这一点?(我更喜欢用PostgreSQL方言的回复)
下面是您可以尝试的查询:
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在这里。