2012-11-29 52 views
1

选择数据我有两个表,即SQL查询从两个表中

邀请

  • InvitationID
  • 用户名
  • 电子邮件

用户

  • 用户名
  • 用户名

我有数据,这两个表

邀请表数据

29 NULL [email protected] 
40 8  [email protected]                  
41 8  [email protected]  

用户表数据

8  [email protected] 

现在我要选择从Invitation表中的所有数据,并且还希望从Users表,其中Invitation.InvitationID等于Users.UserID选择Username

我用这个下面的查询选择数据

SELECT 
    Invitations.*, Users.UserName 
FROM 
    Invitations 
INNER JOIN 
    Users ON Invitations.UserID = Users.UserID 

但它返回只有两排。我想选择Invitation表中的所有行。如果Invitation.UserIDnull那么Username也是null。我想输出是这样的:

29 NULL [email protected] Null 
40 8  [email protected] [email protected]                 
41 8  [email protected] [email protected] 
+3

使用LEFT OUTER JOIN。 –

回答

4

你必须使用左侧加入:

SELECT Invitations.*, Users.UserName 
FROM  Invitations left JOIN 
       Users ON Invitations.UserID = Users.UserID