2

我需要一个只有一个成员的团队列表。

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
3      Fish
5      Pigs

(这与之前提出的问题相反:请不要打败我!)

4

2 回答 2

2
SELECT t.ID, t.Name
FROM Teams t
JOIN Players p ON t.ID=p.Team_ID
GROUP BY t.ID
HAVING COUNT(DISTINCT p.ID) = 1;
于 2013-05-28T20:38:06.687 回答
2
select t.id, t.name
from teams t
join players p on p.team_id = t.id
group by t.id, t.name
having count(*) = 1
于 2013-05-28T20:40:42.460 回答