5

我有两张表,一张用于团队,一张用于玩家我想找出的是总人数表,换句话说,我想计算有 2 名成员的团队总数,即所有团队数量有 3 个成员等

这是数据库结构。

(边栏问题:我是新手:有没有更好的方法来发布 SQL?)

CREATE  TABLE `formsfiles`.`Teams` (
  `ID` INT NOT NULL AUTO_INCREMENT ,
  `Name` VARCHAR(45) NULL ,
  PRIMARY KEY (`ID`) );


INSERT INTO `Teams` (`Name`) VALUES ('Sharks');
INSERT INTO `Teams` (`Name`) VALUES ('Jets');
INSERT INTO `Teams` (`Name`) VALUES ('Fish');
INSERT INTO `Teams` (`Name`) VALUES ('Dodgers');


CREATE  TABLE `Players` (
  `ID` INT NOT NULL AUTO_INCREMENT ,
  `Name` VARCHAR(45) NULL ,
  `Team_ID` INT NULL ,
  PRIMARY KEY (`ID`) );

INSERT INTO `Players` (`Name`, `Team_ID`) VALUES ('Jim', '1');
INSERT INTO `Players` (`Name`, `Team_ID`) VALUES ('Tom', '1');
INSERT INTO `Players` (`Name`, `Team_ID`) VALUES ('Harry', '2');
INSERT INTO `Players` (`Name`, `Team_ID`) VALUES ('Dave', '2');
INSERT INTO `Players` (`Name`, `Team_ID`) VALUES ('Tim', '3');
INSERT INTO `Players` (`Name`, `Team_ID`) VALUES ('Trey', '4');
INSERT INTO `Players` (`Name`, `Team_ID`) VALUES ('Jay', '4');
INSERT INTO `Players` (`Name`, `Team_ID`) VALUES ('Steve', '4');
INSERT INTO `Players` (`Name`, `Team_ID`) VALUES ('Chris', '4');

我想要的是计数团队规模。

我想看到以下输出

Team_Size  Count
1          1
2          2
4          1
4

2 回答 2

3

最简单的方法可能是:

select team_count, count(*) from
(select count(*) team_count from players group by team_id) sq
group by team_count

(尽管这不包括没有球员的球队。)

SQLFiddle在这里

于 2013-05-21T18:05:08.143 回答
3

首先,您需要团队规模:

select t.id as teamId, count(p.id) as teamSize
from 
    `Teams` as t
    left join `Players` as p on t.id = p.teamId
group by
    t.id;

请注意,这也将返回零玩家的团队。如果您不希望这样,请使用inner join而不是left join.

现在,将此查询用作最终查询的行源:

select teamSize, count(teamId)
from (
    select t.id as teamId, count(p.id) as teamSize
    from 
        `Teams` as t
        left join `Players` as p on t.id = p.teamId
    group by
        t.id) as a
group by teamSize;

希望这可以帮助


还有一件事。

如果您有大数据集,此查询可能会挂起。所以最好创建一个临时表,对其进行索引,然后在临时表上运行查询:

drop table if exists temp_teamSize;
create temporary table temp_teamSize
    select t.id as teamId, count(p.id) as teamSize
    from 
        `Teams` as t
        left join `Players` as p on t.id = p.teamId
    group by
        t.id;
alter table temp_teamSize
    add unique index idx_teamId(teamId),
    add index idx_teamSize(teamSize);
select teamSize, count(teamId)
from temp_teamSize
group by teamSize;
于 2013-05-21T18:05:18.627 回答