当我没有在myComputer表中设置ProcessorID时,我的查询不起作用 当我没有在ProcessorID中指定值时,如何生成一个显示ProcessorName的查询,否则当我没有?时显示NULL?
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";
如果尚未设置processorID,则上面的select查询当前返回null。
答案 0 :(得分:7)
如果未为计算机分配处理器,则当前查询不返回任何行,如您提供的示例所示。
您可能希望使用left outer join,而不是使用的隐式inner join:
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";
返回:
+---------------+--------------+
| ProcessorName | ComputerName |
+---------------+--------------+
| NULL | Newton |
+---------------+--------------+
1 row in set (0.00 sec)
答案 1 :(得分:2)
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"