I have 2 tables named user
and userFriend
. I want all user from user table, and specific member from userFriend table. Then I want to join both of them...
user
userID userName
1 aaa
2 bbb
3 ccc
4 ddd
5 eee
userFriend
userFriendID userID friendUserID
1 1 2
2 2 3
3 1 4
4 4 2
So if my userID = 1, then I want result like
userID userName userFriendID friendUserID
2 bbb 1 2
3 ccc NULL NULL
4 ddd 3 4
5 eee NULL NULL
so in this way I want conditional for 2nd table, I only want to join 2nd table having userID = 1 with 1st table using left join.
The LEFT JOIN condition is used to decide how to retrieve rows from table 2nd_table. If there is a row in 1st_table that matches the WHERE clause, but there is no row in 2nd_table that matches the ON condition, an extra 2nd_table row is generated with all columns set to NULL.
The Left Join in SQL basically returns all records from the left table and the matched records from the right tables. For example, let's say, we have two tables, Table A and Table B. When Left Join is applied on these two tables, all records from Table A and only the matched records from Table B will be displayed.
SELECT column names FROM table1 LEFT JOIN table2 ON table1. matching_column = table2. matching_column; Note: For example, if you have a left table with 10 rows, you are guaranteed to have at least 10 rows after applying join operation on two tables.
It's an unconventional thing to ask for... but this gives you the results you want.
SELECT u.userID, u.userName, uf.userFriendID, uf.friendUserID
FROM user u
LEFT JOIN userFriend uf ON u.userID = uf.friendUserID AND uf.userID =1
WHERE u.userID !=1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With