获取记录列表

时间:2013-05-28 17:22:11

标签: mysql

我想列出一个体育联盟中所有队员的名单,这些队员只有一名队员。

这是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');
INSERT INTO `Teams` (`Name`) VALUES ('Pigs');

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 ('Ziggy', '5');
INSERT INTO `Players` (`Name`, `Team_ID`) VALUES ('Chris', '4');

结果应该给我:

ID         Name
5          Tim
9          Ziggy

不确定如何将它们分组?

2 个答案:

答案 0 :(得分:3)

如果您想让只有一名成员的球队退回,您可以使用:

select p.id, p.name
from players p
where p.Team_ID in (select Team_ID
                    from players p
                    group by Team_ID
                    having count(Team_ID) = 1);

请参阅SQL Fiddle with Demo

编辑,您也可以使用(从评论中移动):

select max(id) id, max(name) name
from players 
group by team_id
having count(team_id) = 1;

请参阅SQL Fiddle with Demo

答案 1 :(得分:0)

谢谢Bluefeet:

这项工作很精彩:

我想在此处发布,以防将来有人宣传:

select max(id) id, max(name) name
from players 
group by team_id
having count(team_id) = 1;