2

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:

enter image description here

1
  • 2
    Sample data and desired results is helpful. Commented May 16, 2021 at 19:25

1 Answer 1

1

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 ;
Sign up to request clarification or add additional context in comments.

1 Comment

Unbelievable! Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.