当我没有在myComputer表中设置ProcessorID时,我的查询不起作用当我没有在ProcessorID中指定值时,我怎么能创建一个显示ProcessorName的查询?
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";
Run Code Online (Sandbox Code Playgroud)
如果尚未设置processorID,则上面的select查询当前返回null.
如果未为计算机分配处理器,则当前查询不返回任何行,如您提供的示例所示.
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";
Run Code Online (Sandbox Code Playgroud)
返回:
+---------------+--------------+
| ProcessorName | ComputerName |
+---------------+--------------+
| NULL | Newton |
+---------------+--------------+
1 row in set (0.00 sec)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2580 次 |
| 最近记录: |