我的数据库中有 3 个表,我需要执行一个查询,从一个表中选择所有行,并将其与下面两个表的列的总和连接起来,然后根据该总和进行排序。 table 是用来玩游戏的。您有一个团队表、一个用户表,其中用户是唯一的并分配给一个团队,其中 users.team_id = groups.id 列,最后一个项目表,其中每个人每天收集的项目。该人每天输入收集的元素数量,然后将其汇总为总数。 items 表由 users.adid = items.user_id 连接。
我需要的是一个选择查询,它将为我提供所有团队的列表,仅限于日期在 2015 年以内的团队,然后有一列用于显示每个团队收集的项目总和,每个团队可以有多个团队成员。然后,这一切都按项目数量从最大到最小排序。
示例:
| Team ID | Team Name | Total Items |
-------------------------------------
| 1 | Bravo | 5674 |
| 567 | Charlie | 16 |
等等
我尝试过使用MySQL SUM(),但我遇到的问题是连接、分组或嵌套查询,这需要获取每个团队的每个用户项目的总和。
表结构:
CREATE TABLE `teams` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL DEFAULT '',
`captain_id` varchar(11) NOT NULL DEFAULT '',
`date` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `users` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`team_id` int(11) NOT NULL,
`adid` varchar(12) NOT NULL DEFAULT '',
`email` varchar(100) NOT NULL DEFAULT '',
`first_name` varchar(100) DEFAULT '',
`last_name` varchar(100) DEFAULT '',
PRIMARY KEY (`id`),
UNIQUE KEY `ADID` (`adid`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `items` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`user_id` varchar(11) NOT NULL DEFAULT '0',
`items` int(3) NOT NULL DEFAULT '0',
`date` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
最佳答案
这应该可以解决问题:
SELECT t.id, t.name, sum(i.items) as totalItems /* you will get 3 columns as result: "id", "name" and "totalItems" */
FROM teams t /* start selecting from the table "teams"... */
INNER JOIN users u ON u.team_id = t.id /* ... join the users table ... */
INNER JOIN items i ON i.user_id = u.adid /* ... and last but not least the items table */
WHERE year(t.date) = 2015 /* filter the teams by year */
GROUP BY t.id /* group the result by team id - you want just one line per team */
ORDER BY totalItems DESC /* order by total items */
我看到您的项目表中还有一个日期 - 如果您也想过滤该年份的日期,请执行以下操作:
SELECT t.id, t.name, sum(i.items) as totalItems /* you will get 3 columns as result: "id", "name" and "totalItems" */
FROM teams t /* start selecting from the table "teams"... */
INNER JOIN users u ON u.team_id = t.id /* ... join the users table ... */
INNER JOIN items i ON i.user_id = u.adid AND year(i.date) = 2015 /* ... and last but not least the items table (and filter by year) */
WHERE year(t.date) = 2015 /* filter the teams by year */
GROUP BY t.id /* group the result by team id - you want just one line per team */
ORDER BY totalItems DESC /* order by total items */
为了将 items-table 与 user-table 连接起来,您当前正在将 int 与 varchar 连接 - (items.user_id with users.adid) - 为什么不将 items.user_id 与 users.id 连接起来?如果这不可能,我建议将 adid 从 varchar 切换为 int。
关于MySQL多表选择SUM查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28153090/