我遇到了一个有趣的问题,下表中有一个NULL值:
CREATE TABLE dbo.STAFF (
staffID int PRIMARY KEY NOT NULL,
lastname varchar(50) NULL,
firstname varchar(50) NULL,
pay money NULL,
supervisorID int NULL
)
INSERT INTO STAFF (staffID, lastname, firstname, pay, supervisorID)
VALUES (1, 'Smith', 'John', 60000, NULL),
(2,'Jones', 'Bridget', 13000, 1),
(3,'Robinson', 'Smokey', 14000, 1),
(4, 'Vedder', 'Eddie', 13000, 3),
(5, 'Almighty', 'Bruce', 12000, 2),
(6, 'Addington', 'Jane', 11000, 2),
(7, 'Hogan', 'Hulk', 10000, 3),
(8, 'Jackson', 'Jacky', 15000, 2),
(9, 'Samuelson', 'Sammy', 14400, 1)
;
当我运行此查询时,第一行未返回,并且由于null值,它似乎被忽略。为什么这不起作用。我假设它与自连接中的CASE语句中的NULL值有关?我真的很感兴趣为什么这不起作用。
SELECT (a.firstname + ' ' + a.lastname) AS "Employee Name",
CASE
WHEN a.supervisorID IS NOT NULL THEN (b.firstname + ' ' + b.lastname)
ELSE 'No supervisor'
END AS "supervisor Name"
FROM dbo.STAFF a, dbo.STAFF b
WHERE a supervisorID= b.staffID;
答案 0 :(得分:2)
你可以试试这个:
SELECT (a.firstname + ' ' + a.lastname) AS "Employee Name",
CASE
WHEN a.supervisorID IS NOT NULL THEN (b.firstname + ' ' + b.lastname)
ELSE 'No supervisor'
END AS "supervisor Name"
FROM dbo.STAFF a
LEFT JOIN dbo.STAFF b
WHERE a supervisorID= b.staffID;
答案 1 :(得分:1)
你必须使用LEFT JOIN。我想如果连接类型没有给INNER JOIN是默认的。
答案 2 :(得分:0)
多亏了这一点,对查询稍作修改就可以了。)
SELECT (a.firstname + ' ' + a.lastname) AS "Employee Name",
CASE
WHEN a.supervisorID IS NOT NULL THEN (b.firstname + ' ' + b.lastname)
ELSE 'No supervisor'
END AS "supervisor Name"
FROM dbo.STAFF a
LEFT JOIN dbo.STAFF b
ON a.supervisorID = b.staffID;