简体   繁体   中英

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

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

Try with a LEFT JOIN query

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

I'd like you have a look at this visual representation of JOIN query

Right join keeps all results from the 2nd table (it keeps all results on the right-hand table), you want a left join, or swap the positions of user and account in the join clause.

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

I believe that should do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM