Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write conditional left join

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.

like image 415
sneha Avatar asked Nov 22 '10 07:11

sneha


People also ask

WHAT IS A LEFT join condition?

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.

What is LEFT join with example?

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.

How do I join two tables with left join in SQL?

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.


1 Answers

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
like image 130
Riedsio Avatar answered Oct 13 '22 04:10

Riedsio