即使第二个表上的行不存在,也要正确连接

时间:2013-06-07 15:07:10

标签: mysql sql

我想连接两个表,即使第二个表没有匹配。

表用户:

uid | name
1     dude1
2     dude2

表帐户:

uid | accountid | name
1     1           account1

我想要的表:

uid  | username | accountname
1      dude1      account1
2      dude2      NULL

我正在尝试的查询:

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

我得到了什么:

uid  | username | accountname
1      dude1      account1

3 个答案:

答案 0 :(得分:31)

使用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

答案 1 :(得分:4)

尝试使用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

我希望您看一下JOIN query

的视觉表现形式

答案 2 :(得分:4)

右连接保留第二个表中的所有结果(它将所有结果保留在右侧表中),您需要左连接,或者在连接子句中交换用户和帐户的位置。

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

我相信应该这样做。