I have 2 tables users and referral.
here is the structure of 2 tables.
referral table
| Column | ---------------- | ref_id | | from_user_id | | to_user_id | | ref_name | | ref_phone | | ref_email | | ref_note |
users table
| Column | ---------------- | user_id | | user_name | | user_first_name | | user_last_name | | user_email | | user_phone |
i have 2 sections where a user can see received and sent referrals.
in received referral section how do i get the first_name and last_name from users table joining the from_user_id in referral table.
so far i came up with this query for received referral which gets me the intended result set. but how can get the users table firstname and lastname from referral table from_user_id
SELECT users.user_id, users.user_name, users.user_firstname, users.user_lastname, referral.ref_name, referral.ref_phone, referral.ref_email, referral.ref_note FROM referral JOIN users ON referral.to_user_id = users.user_id WHERE referral.to_user_id = (logged in user id)
similarly in the sent referral section how do i get the user firstname and lastname joining users and referral table from_user_id key
SELECT users.user_id, users.user_name, users.user_firstname, users.user_lastname FROM referral JOIN users ON referral.from_user_id = users.user_id WHERE referral.from_user_id = (logged in user id)
any help would be greatly appreciated.
Advertisement
Answer
I think you want two joins on the users table:
select r.ref_name, r.ref_phone, r.ref_email, r.ref_note, uf.user_id as from_user_id, uf.user_name as from_user_name, uf.user_firstname as from_user_firstname, uf.user_lastname as from_user_lastname, ut.user_id as to_user_id, ut.user_name as to_user_name, ut.user_firstname as to_user_firstname, ut.user_lastname as to_user_lastname from referral r inner join users ut on r.to_user_id = ut.user_id inner join users uf on r.from_user_id = uf.user_id where r.to_user_id = ?