我有两张 table ,一张有一组团队以及有关他们的信息。另一张表包含有关他们玩过的游戏的信息。我想计算某个特定球队打了多少场比赛。
我在名为 team 的表上有 team_number、team_name。我在另一个名为 Play 的表上有 Played_Team,这是 team_number 的外键。
如何编写一个连接来计算 Played_team 出现的次数并使用 team_number 和 team_name 加入它?
我正在使用 MYSQL 5.1,我希望这是有意义的。 谢谢
最佳答案
怎么样:
select teams.`team_name`, count(matches.`played_team`)
from teams
join matches on teams.`team_number` = matches.`played_team`
group by teams.`team_name`
这是我使用的表格:
CREATE TABLE `teams` (
`team_number` int(11) NOT NULL AUTO_INCREMENT,
`team_name` varchar(30) DEFAULT NULL,
PRIMARY KEY (`team_number`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `teams` (`team_number`, `team_name`)
VALUES
(1,'a'),
(2,'b'),
(3,'c'),
(4,'d');
CREATE TABLE `matches` (
`played_team` int(11) NOT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
`match_title` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `played_team` (`played_team`),
CONSTRAINT `matches_ibfk_1` FOREIGN KEY (`played_team`) REFERENCES `teams` (`team_number`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `matches` (`played_team`, `id`, `match_title`)
VALUES
(1,1,'match_a'),
(1,2,'match_b'),
(3,3,'match_c'),
(4,4,'match_d');
以下是查询结果:
team_name count(matches.`played_team`)
a 2
c 1
d 1
关于mysql - 在连接上使用计数 - MYSQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13634416/