Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting List of records with No related records MySQL

Tags:

mysql

I wish to know which team in "TX" have not played a game. (In other words Im looking for a selection of records where there is no related record in the many table.)

Here is the SQL:

(Or if You prefer the sql fiddle is here: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');

I should get the result:

ID     Name    
1      Rams
7      Bolts
like image 811
JVMX Avatar asked Dec 04 '22 10:12

JVMX


1 Answers

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

SqlFiddle here.

like image 50
vidit Avatar answered Jan 11 '23 09:01

vidit