coiso coiso - 6 months ago 17
SQL Question

right join even if row on second table does not exist

I want to join two tables even if there is no match on the second one.

table user:

uid | name
1 dude1
2 dude2


table account:

uid | accountid | name
1 1 account1


table i want:

uid | username | accountname
1 dude1 account1
2 dude2 NULL


the query i'm trying with:

SELECT user.uid as uid, user.name as username, account.name as accountname
FROM user RIGHT JOIN account ON user.uid=accout.uid


what i'm getting:

uid | username | accountname
1 dude1 account1

Answer

use Left Join instead

SELECT user.uid as uid, user.name as username, account.name as accountname
FROM user LEFT JOIN account ON user.uid=accountid.uid