Jump to content

How would you join two columns in the same table?


imgrooot
Go to solution Solved by imgrooot,

Recommended Posts

Basically i want to match 2 columns from table1 to 1 column in table2.  

 

Here's my code. How do I do the joins properly?

$get_earnings = $db->prepare("SELECT users.*, member_earnings.* FROM member_earnings
LEFT JOIN users ON member_earnings.sent_by = users.user_id
LEFT JOIN users ON member_earnings.guest_id = users.user_id
WHERE record_id = :record_id AND status = :status ORDER BY earning_id DESC LIMIT 20");
$get_earnings->bindParam(':record_id', $url_id);
$get_earnings->bindValue(':status', 1);
$get_earnings->execute();
Edited by imgrooot
Link to comment
Share on other sites

If you join the same table multiple times, you need to give the joins an alias so you can distinguish between them.

 

SELECT sentBy.*, guest.*, member_earnings.* 
FROM member_earnings
LEFT JOIN users as sentBy ON member_earnings.sent_by = sentBy.user_id
LEFT JOIN users as guest ON member_earnings.guest_id = guest.user_id
WHERE record_id = :record_id AND status = :status 
ORDER BY earning_id DESC LIMIT 20
Link to comment
Share on other sites

  • Solution

If you join the same table multiple times, you need to give the joins an alias so you can distinguish between them.

 

SELECT sentBy.*, guest.*, member_earnings.* 
FROM member_earnings
LEFT JOIN users as sentBy ON member_earnings.sent_by = sentBy.user_id
LEFT JOIN users as guest ON member_earnings.guest_id = guest.user_id
WHERE record_id = :record_id AND status = :status 
ORDER BY earning_id DESC LIMIT 20

 

Perfect. That works like a charm. Thank you.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.