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.
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:
Returns: