获取没有相关记录的记录列表MySQL

时间:2013-05-29 02:54:50

标签: mysql

我想知道“TX”中的哪支球队没有参加比赛。 (换句话说,我在寻找许多表中没有相关记录的记录选择。)

这是SQL:

(或者,如果您更喜欢sql小提琴,请访问:http://sqlfiddle.com/#!2/14106

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

CREATE  TABLE `Games` (
  `ID` INT NOT NULL AUTO_INCREMENT,
  `Team_ID` INT NULL ,
  `Game_Day` DATE NULL ,
  PRIMARY KEY (`ID`) );

    INSERT INTO `Team` (`Name`, `State`) VALUES ('Rams', 'TX');
    INSERT INTO `Team` (`Name`, `State`) VALUES ('Rockets', 'OK');
    INSERT INTO `Team` (`Name`, `State`) VALUES ('Bombers', 'TX');
    INSERT INTO `Team` (`Name`, `State`) VALUES ('Yellow Jackets', 'NV');
    INSERT INTO `Team` (`Name`, `State`) VALUES ('Wildcats', 'CT');
    INSERT INTO `Team` (`Name`, `State`) VALUES ('Miners', 'CO');
    INSERT INTO `Team` (`Name`, `State`) VALUES ('Bolts', 'TX');

    INSERT INTO `Games` (`Team_ID`, `Game_Day`) VALUES ('2', '2013-03-16');
    INSERT INTO `Games` (`Team_ID`, `Game_Day`) VALUES ('2', '2013-01-01');
    INSERT INTO `Games` (`Team_ID`, `Game_Day`) VALUES ('3', '2013-04-16');
    INSERT INTO `Games` (`Team_ID`, `Game_Day`) VALUES ('5', '2013-02-02');
    INSERT INTO `Games` (`Team_ID`, `Game_Day`) VALUES ('4', '2013-02-12');
    INSERT INTO `Games` (`Team_ID`, `Game_Day`) VALUES ('6', '2013-01-09');
    INSERT INTO `Games` (`Team_ID`, `Game_Day`) VALUES ('6', '2013-01-01');
    INSERT INTO `Games` (`Team_ID`, `Game_Day`) VALUES ('3', '2013-05-01');

我应该得到结果:

ID     Name    
1      Rams
7      Bolts

4 个答案:

答案 0 :(得分:4)

使用外部联接,仅选择匹配的行

SELECT t.*
FROM TEAM t
LEFT JOIN GAMES g ON g.team_id = t.id
WHERE t.state = 'TX'
AND g.team_id is null -- return only rows that *don't* join

这在SQL Fiddle

中运行

请注意,使用连接将超出子查询方法,尤其是在数据集变大时。

答案 1 :(得分:3)

SELECT `ID`, `Name` FROM `TEAM` 
  WHERE `ID` NOT IN (SELECT DISTINCT(`Team_ID`) from `Games`) 
  AND `State` = 'TX'; 

SqlFiddle here

答案 2 :(得分:3)

您也可以左键加入Games表,并过滤掉没有相应Games行的位置。当表有很多行时,这通常比NOT IN更快:

SELECT Team.ID, Team.Name
FROM Team
LEFT JOIN Games ON Team.ID = Games.Team_ID
WHERE Team.State = 'TX' AND Games.ID IS NULL;

如果Games行中没有Teams行,则Games.ID列在结果中将为空,因此如果您对Games.ID IS NULL进行过滤你将获得团队没有游戏的所有行。

有一个SQL小提琴here

答案 3 :(得分:1)

希望这会有所帮助。

select t.ID,t.NAME
FROM Team t
WHERE t.state = 'TX'
AND t.id NOT IN (SELECT g.TEAM_ID FROM Games g)