MySQL 即使第二个表上的行不存在,右连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16987322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 17:53:07  来源:igfitidea点击:

right join even if row on second table does not exist

mysqlsql

提问by coiso

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

回答by Gonzalo.-

use Left Joininstead

使用Left Join替代

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

回答by Fabio

Try with a LEFT JOINquery

尝试LEFT JOIN查询

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 JOINquery

我想让你看看这个查询的可视化表示JOIN

回答by Brett Rossier

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.

我相信应该这样做。