Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL left join on multiple fields

Tags:

join

mysql

I have a friends table. Is it possible to do a left join on two fields of the table. In other words, I don't know which of the two fields may have the match I need. If not is there another way to do this?

$sql = "SELECT * FROM `friends` f
LEFT JOIN `users` u
ON f.askee OR f.asker = u.ID
where (asker='$userid' OR askee='$userid') AND status='3'";
like image 877
user1260310 Avatar asked Apr 14 '26 12:04

user1260310


1 Answers

The left join is correct: the OR operator will do what you expect. But then your filter on $userid should apply to the parent table (friends), not left joined one (otherwise it would cancel the outer join):

$sql = "SELECT * FROM `friends` f
LEFT JOIN `users` u ON f.`askee` = u.`ID` OR f.`asker` = u.`ID`
WHERE u.`status` = '3' AND u.ID = '$userid'";
like image 93
Sebas Avatar answered Apr 16 '26 01:04

Sebas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!