0

这很棘手,我的任务是创建一个团队领导委员会,个人完成任务以获得分数。分数在“站”表中定义,每次用户完成任务时,都会在帖子表中创建一个帖子,其中包含站的 ID 及其 RFID(射频 ID)。有一个定义团队名称的团队表。

我需要一种方法来获取团队成员参与的所有帖子分数的总和(从站表中加入的分数)。

结果应该按团队得分排序,看起来像如果我们有 4 个团队,有 4 名成员参加了 4 个项目 - 每个团队的总得分是多少

Team name one (Teams.name) | score

Team name two (Teams.name) | score

Team name three (Teams.name) | score

桌子 -

CREATE TABLE `posts` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `rfid` varchar(50) NOT NULL,
  `station_id` int(11) NOT NULL,
  `updated_at` datetime NOT NULL,
  `created_at` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;

-- --------------------------------------------------------

表的表结构stations

CREATE TABLE `stations` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `description` text NOT NULL,
  `points` int(11) NOT NULL,
  `logic` varchar(200) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1023 ;

-- --------------------------------------------------------

表的表结构teams

CREATE TABLE `teams` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;

-- --------------------------------------------------------

表的表结构users

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `rfid` varchar(50) NOT NULL,
  `first_name` varchar(50) NOT NULL,
  `last_name` varchar(50) NOT NULL,
  `team` int(11) NOT NULL,
  `quiz_score` int(11) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

我为个人排行榜创建了一个查询-

SELECT users.first_name, users.last_name, posts.rfid, sum(stations.points) score 
FROM posts 
JOIN users ON posts.rfid = users.rfid  
JOIN stations ON posts.station_id = stations.id  
GROUP BY posts.rfid 
ORDER BY score DESC LIMIT 0 , 100

这就是我迄今为止为第一队所做的

SELECT name, (SELECT sum(stations.points) score FROM posts 
      JOIN users ON posts.rfid = users.rfid 
      JOIN stations ON posts.station_id = stations.id  
  WHERE users.team = teams.id 
      GROUP BY posts.rfid) team_score FROM teams

//subquery returns more than one row

我认为这可能是正确的答案

SELECT name, 
    (SELECT sum(stations.points) score FROM posts
         JOIN users ON posts.rfid = users.rfid 
         JOIN stations ON posts.station_id = stations.id  
      WHERE users.team = teams.id ) team_score 
  FROM teams
4

0 回答 0