给定多个表之间的连接,我想在单个查询中找到列的总和。
我有一个活动表,一个映射用户执行活动的表,以及一个将团队映射到执行活动的表。用户和团队都可以多次执行相同的活动。
每个活动都值得一定数量的积分,我想通过将他们的活动与其团队的活动相加来知道给定用户的总积分数。
我已经尝试了三个表之间的各种连接组合,但无法计算出正确的查询来计算给定用户的总分。
以下 SQL 将创建此设置的最小版本:
CREATE TABLE `activity` (
`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL DEFAULT '',
`points` INT(10) UNSIGNED NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=INNODB;
CREATE TABLE `team_action` (
`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`activity_id` INT(11) UNSIGNED NOT NULL,
`date` DATETIME NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `team_action_ibfk_1` FOREIGN KEY (`activity_id`) REFERENCES `activity` (`id`)
) ENGINE=INNODB;
CREATE TABLE `user_action` (
`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`activity_id` INT(11) UNSIGNED NOT NULL,
`date` DATETIME NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `user_action_ibfk_1` FOREIGN KEY (`activity_id`) REFERENCES `activity` (`id`)
) ENGINE=INNODB;
INSERT INTO `activity` (`id`, `name`, `points`)
VALUES (1,'Running',10), (2,'Swimming',20), (3,'Hiking',30), (4,'Cycling',40);
INSERT INTO `team_action` (`id`, `activity_id`, `date`)
VALUES (1,2,'2012-05-22 14:32:31'), (2,4,'2012-05-22 14:32:36');
INSERT INTO `user_action` (`id`, `activity_id`, `date`)
VALUES (1,1,'2012-05-22 14:32:08'), (2,1,'2012-05-22 14:32:18'), (3,3,'2012-05-22 14:32:23');