我在论坛上搜索了我的问题的解决方案。我的问题 是我无法找到如何保存每个锦标赛的排名位置 这是举行。我创建了两个表和一个如下所示的查询: 竞争对手(cid int auto_increment主键,名称varchar(25),lastname varchar(25)); comps(compid int auto_increment primary key,tournement int,cid int,points int);
select @rowno:= @rowno+1 as position, rank.*
from (
select name,lastname,SUM(points) as pts,group_concat(points) as round FROM
(select cid,tournament,points from comps
group by cid,tournament order by points)total
join competitors c on c.cid = total.cid
cross join (select @rowno := 0) r
group by total.cid
order by pts desc) rank
order by pts desc
我想要实现的是,当用户点击竞争对手的个人资料时,每个锦标赛的位置都会显示如下:
Name: Competitor One
Tournament 1: 1st 100 pts
Tournament 2: 2nd 80 pts
Tournament 3: 10th 30 pts
我已经对点数进行了分组,但我不知道如何用位置来做到这一点。这可能来自此查询,还是我必须创建一个新的表,如position(pid int auto_increment primary key,tournament int,cid int,position int),我为每个竞争者插入每个位置。
希望有人理解我的问题,并可以给我一些提示或解决这个问题的方法
答案 0 :(得分:1)
如果我的理解是对的,那么我希望这对你有用
select *,(SELECT COUNT(*)
FROM comps AS cmp2
WHERE cmp1.points < cmp2.points AND cmp1.tournament = cmp2.tournament) + 1 AS position
from competitors AS c1
inner join comps AS cmp1 on c1.cid = cmp1.cid
order by c1.name,c1.lastname,cmp1.compid, position ASC
使用Sql Fiddle Here
答案 1 :(得分:0)
如果你想要每场锦标赛的成绩,你可以这样做:
select * from competitors
inner join comps on competitors.cid = comps.cid
order by tournament, points desc
如果您希望将其分组最简单,则使用子查询来总结每个竞争对手的积分:
select *,(select sum(points) from comps where competitors.cid=comps.cid) as points
from competitors
order by points desc
不,你不想要一张有职位的桌子,因为那是计算数据。您想要这样做的唯一原因是出于性能原因(并且每x次自动更新一次)。