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:
I think the JOIN
conditions have the tables inverted:
SELECT c.Id, c.Name, c.ReferredBy, n.Name as ReferredBy_name
FROM Customers c LEFT JOIN
Customers n
ON n.Id = c.ReferredBy ;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.