请协助:复杂的排名查询

时间:2011-12-01 17:37:12

标签: mysql sql relational-database

我正在为一家扑克俱乐部开发一个网站,他们希望展示其玩家的排名。玩家参加比赛,每次投注都会获得预定数量的积分。然后俱乐部会显示按累积积分排列的球员表。

俱乐部在CMS中输入此数据,并且有四个数据库表。这些表的create语句是(为清楚起见,删除了一些字段):

CREATE TABLE `players` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`)
);

CREATE TABLE `players_tournaments` (
  `player_id` int(10) unsigned NOT NULL,
  `tournament_id` int(10) unsigned NOT NULL,
  KEY `player_id` (`player_id`),
  KEY `tournament_id` (`tournament_id`)
);

CREATE TABLE `tournaments` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `date` date NOT NULL,
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL
  PRIMARY KEY (`id`)
);

CREATE TABLE `tournaments_placings` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `tournament_id` int(10) unsigned NOT NULL,
  `player_id` int(10) unsigned NOT NULL,
  `placing_id` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `tournament_id` (`tournament_id`),
  KEY `player_id` (`player_id`),
  KEY `placing_id` (`placing_id`)
);

ALTER TABLE `players_tournaments`
  ADD CONSTRAINT `players_tournaments_ibfk_3` FOREIGN KEY (`player_id`) REFERENCES `players` (`id`),
  ADD CONSTRAINT `players_tournaments_ibfk_4` FOREIGN KEY (`tournament_id`) REFERENCES `tournaments` (`id`);

ALTER TABLE `tournaments_placings`
  ADD CONSTRAINT `tournaments_placings_ibfk_1` FOREIGN KEY (`tournament_id`) REFERENCES `tournaments` (`id`),
  ADD CONSTRAINT `tournaments_placings_ibfk_2` FOREIGN KEY (`player_id`) REFERENCES `players` (`id`),
  ADD CONSTRAINT `tournaments_placings_ibfk_3` FOREIGN KEY (`placing_id`) REFERENCES `placings` (`placing`);

希望它如何与表命名结构联系起来是不言自明的,但外键信息也在那里。

还有第五个表placings,其中有两列:placing_id,它只是一个PRIMARY KEY列;和points,其中存储了该放置应该获得多少积分。

问题:根据我placings表中定义的点数结构,我的查询在所有比赛过程中拉出所有玩家的累积积分会是什么样的?

我已经看过各种各样的解决方案,比如足球联赛表,但是在查询中有分数系统(即3分为胜利,1分为平局,0分为亏损)而我的扑克联赛例子有很多变化,因为它不是赢,输,拉的情况。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

在我看来,您需要加入tournaments_placingsplacings,以便获得与所有完成相关联的点数。

您正在寻找每位玩家的总积分 - 因此您需要group by player_idsum(points)

select 
  player_id, sum(points)
from 
  tournaments_placings
inner join 
  placings
  using(placing_id)
group by 
  player_id;

如果您还想获取播放器信息(而不仅仅是ID),则可以加入players