tags:

views:

39

answers:

2

My Query does not work when I have not set the ProcessorID in myComputer table How can I make a query that will show me the ProcessorName when I have a value assigned in ProcessorID or NULL when I don't?

CREATE TABLE myProcessor
(    
 ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY, 
 Name VARCHAR(255) NOT NULL
) ENGINE=InnoDB;  

INSERT INTO myProcessor (Name) VALUES ("xeon");

CREATE TABLE myComputer 
(
 ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY, 
 Name VARCHAR(255) NOT NULL,
 ProcessorID INT DEFAULT NULL,
 FOREIGN KEY (ProcessorID) REFERENCES myProcessor(ID) ON DELETE CASCADE
) ENGINE=InnoDB;  

INSERT INTO myComputer (Name) VALUES ("Newton");

SELECT p.Name as ProcessorName, c.Name as ComputerName
FROM myComputer c, myProcessor p 
WHERE c.ProcessorID = p.ID
AND c.Name = "Newton";

The above select query currently returns null if the processorID has not been set.

+5  A: 

Your current query returns no rows if a computer is not assigned a processor, as in the example you provided.

You may want to use a left outer join, instead of the implicit inner join you are using:

SELECT     p.Name as ProcessorName, c.Name as ComputerName
FROM       myComputer c
LEFT JOIN  myProcessor p ON (c.ProcessorID = p.ID)
WHERE      c.Name = "Newton";

Returns:

+---------------+--------------+
| ProcessorName | ComputerName |
+---------------+--------------+
| NULL          | Newton       |
+---------------+--------------+
1 row in set (0.00 sec)
Daniel Vassallo
+1  A: 
SELECT p.Name as ProcessorName, m.Name as ComputerName FROM myComputer m
  LEFT JOIN  myProcessor p ON (m.ProcessorID = p.ID)
   WHERE m.Name = "Newton"
Eton B.
@Eton: You have a small typo in there. `c.Name` should be `m.Name`.
Daniel Vassallo
oops, forgot to edit that one after copying your answer
Eton B.