我有两张桌子,一张有一组团队和有关他们的信息。另一张表有关于他们玩过的游戏的信息。我想计算一个特定球队打了多少场比赛。
我在一张名为 team 的表上有 team_number、team_name。我在名为played 的另一张表上有played_team,它是team_number 的外键。
我如何编写一个连接来计算 play_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