LEFT OUTER JOIN有四个表

时间:2014-08-29 11:41:03

标签: mysql sql tsql join left-join

这是表结构

用户表

Column  
fb_id   
email   
name    
fname   
lname   
gender  
fb_link 
created

推荐表

Column
id  
referred_by 
joinee  
created

目前实施的一个SQL是(示例1)

SELECT u.fb_id
    ,fb_link
    ,name
    ,r.referred_by
    ,u.created 
FROM users u 
LEFT OUTER JOIN referral r 
    ON u.fb_id=r.joinee

以上查询的结果

joinee              referer
10152250261037651   NULL
10152604594389921   NULL
10154430845000507   1518673071699780
....
....
....
....
547146735389782     NULL

这是sql(例2)

SELECT u_joinee.fb_id joinee_fb_id
    ,u_referer.fb_id referer_fb_id
    ,u_joinee.NAME joinee_name
    ,u_referer.NAME referer_name
FROM users u_joinee
    ,users u_referer
    ,referral r_j
    ,referral r_r
WHERE u_referer.fb_id = r_r.referred_by
    AND u_joinee.fb_id = r_j.joinee

以上查询的结果

joinee_fb_id        referer_fb_id       joinee_name referer_name
10154430845000507   1518673071699780    Saselsdein  Bsdasd

我要注意的是我在输出中需要joinee_namereferer_name两个名称。但我无法在LEFT OUTER JOIN子句中使用四个表,就像我在例如1中所做的那样我想要获取包括非推荐和推荐参与者的两个记录是否有任何方法可以期望所需的结果如下所示

预期结果

joinee_fb_id        referer_fb_id       joinee_name referer_name
10154430845000507   1518673071699780    Saselsdein  Bsdasd
10154430845000347   Null                asd         NULL
10154430845000567   Null                asd asdm    NULL
10154230845000567   Null                Dsd asdm    NULL
10154330845000567   Null                sdm         NULL
101544553045000567  Null                Esd aedm    NULL

1 个答案:

答案 0 :(得分:2)

您可以通过为users表提供不同的别名来加入referral表,就像使用隐式内连接一样。

我认为你不需要加入referral两次。 SELECT u_joinee.fb_id joinee_fb_id ,u_referer.fb_id referer_fb_id, u_joinee.name joinee_name, u_referer.name referer_name FROM users AS u_joinee LEFT JOIN referral AS r ON r.joinee = u_joinee.fb_id LEFT JOIN users AS u_referer ON r.referred_by = u_referer.fb_id 表中的一行链接引荐来源和被邀请者。

{{1}}