I want to show the names of the customers along with the names of those who referred them. I thought I was on the right track but the result is messed up. I tried conditions ReferredBy NOT NULL
in WHERE
clause, ReferredBy NOT NULL
in ON
clause - no luck.
I would appreciate any help!
sqlfiddle
CREATE TABLE Customers(
Id int NOT NULL,
Name varchar(50) NOT NULL,
ReferredBy int REFERENCES Customers(Id),
PRIMARY KEY (Id)
);
INSERT INTO Customers VALUES
(11, 'Peter', 22),
(22, 'Ariel', NULL),
(33, 'Tom', 11);
My approach:
SELECT c.Id, c.Name, c.ReferredBy, n.Name as ReferredBy_name
FROM Customers c
LEFT JOIN Customers n
ON c.Id = n.ReferredBy
Desired Output: