在Join上使用Count - MYSQL

时间:2012-11-29 20:45:32

标签: mysql join count

我有两张桌子,一张有一组球队,有关他们的信息。另一张表有关于他们玩过的游戏的信息。我想算一下特定球队的比赛数量。

我在一个名为team的表上有team_number,team_name。我在另一个名为playing的表上有play_team,这是team_number的外键。

如何编写联接来计算playing_team的出现次数并将其与team_number和team_name连接?

我正在使用MYSQL 5.1,我希望这是有道理的。 感谢

1 个答案:

答案 0 :(得分: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