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