Skip to content
Advertisement

SQL JOIN and desired a view: 2 foreign keys referencing the same table

I feel I can’t solve my task without community help. Unfortunately, my knowledge of SQL is weak.

I have 2 tables – user and referral which represents data about senders and referral of senders (sender can have a 1..n referral, but referral can have only one sender).

I would like to create 2 queries – get all referrals for the specific sender and other ones to get sender for the specific referral.

For getting all referrals:

Output:

For getting sender for the specific referral:

Output:

Everything is ok except referral output. I would like to view referral name instead of id.

Also I would like to get output for sender of specific referral only sender name, without the second column referral, because there is one-to-one relationship.

Could anyone to help me understand join in my case?!

Thank you in advance!

Advertisement

Answer

You want to join to users twice:

Notes:

  • You need table aliases so you can refer the same table multiple times in the FROM clause.
  • This logic uses LEFT JOIN, in case one of the columns is empty.
  • You should be passing in the requested sender id using a parameter, which is why I’ve used ? as a parameter placeholder.
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement