2

给定多个表之间的连接,我想在单个查询中找到列的总和。

我有一个活动表,一个映射用户执行活动的表,以及一个将团队映射到执行活动的表。用户和团队都可以多次执行相同的活动。

每个活动都值得一定数量的积分,我想通过将他们的活动与其团队的活动相加来知道给定用户的总积分数。

我已经尝试了三个表之间的各种连接组合,但无法计算出正确的查询来计算给定用户的总分。

以下 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');
4

1 回答 1

1

从表定义中不清楚用户与团队的关系(即对于用户,你怎么知道哪个是“他们的”团队?)但我认为总结积分的关键是SUM使用UNION ALLin一个子查询。

类似于以下内容:

SELECT SUM(points) AS total
FROM
(SELECT points
 FROM team_action JOIN activity ON(activity.id = team_action.activity_id)
 WHERE team_action.id = my_team
 UNION ALL
 SELECT points
 FROM user_action JOIN activity ON(activity.id = user_action.activity_id)
 WHERE user_action.id = my_user) me_and_team
于 2012-05-22T05:38:04.007 回答