2014-09-29 83 views
1

对不起问这样一个新手问题,但我一直在试图理解这个SQL查询并添加一个东西,我不能做到这一点。如何在sql查询中使用两个连接?语法

下面是该查询:

select 
    p.id, p.nick, p.creation_date 
from 
    tb_player p 
left outer join 
    tb_invoice i on (i.player_id = p.id), tb_player_last_login tpl 
where 
    p.creation_date < now() - '12 months'::interval 
    and tpl.last_login_date < now() - '12 months'::interval 
    and tpl.player_id = p.id 
    and p.id > 9999 
    and (p.email = 'EDITE-SEU-EMAIL' or p.email = 'configure-seu-email') 
    and i.id is null 
limit 15000; 

所以我从这个tb_player选择一组的人,我有另一个表称为tb_email_list,我需要的地方说包括具有的tb_player球员相同的电子邮件地址tb_email_list有效。

  • tb_player有缺口和电子邮件阵营
  • tb_email_list player_id,电子邮件,is_valid

我试图把一些加入,但没有我这样做似乎工作...

有一点帮助请?

我的朋友帮我,它会像

select p.id, p.nick, p.creation_date 
from tb_player_last_login tpl, tb_player p 
left outer join tb_invoice i on (i.player_id = p.id) 
left join tb_email_list e on e.player_id = p.id 
where p.creation_date < now() - '12 months'::interval 
and tpl.last_login_date < now() - '12 months'::interval 
and tpl.player_id = p.id 
and p.id > 9999 
and (p.email = 'EDITE-SEU-EMAIL' or p.email = 'configure-seu-email' or e.is_valid = -1) 
and i.id is null 
limit 15000 

感谢您的帮助

+1

您不应该突然混合使用*适当* ANSI JOIN('INNER JOIN','LEFT OUTER JOIN')与旧的,不推荐的*逗号分隔的列表* JOIN的样式 - 使用** 1 **样式(最好是**显式** JOIN关键字!)并坚持下去!在查询 – 2014-09-29 16:35:22

回答

1

只需要添加另外加入这样的:

select 
    p.id, p.nick, p.creation_date 
from 
    tb_player p 
inner join tb_player_last_login tpl on tpl.player_id = p.id 
left outer join tb_invoice i on i.player_id = p.id 
left outer join tb_email_list l on p.id = l.player_id 
where 
    p.creation_date < now() - '12 months'::interval 
    and tpl.last_login_date < now() - '12 months'::interval 
    and p.id > 9999 
    and i.id is null 
    and (p.email = 'EDITE-SEU-EMAIL' or p.email = 'configure-seu-email') 
limit 15000; 

请注意,为了确保一致性,我还添加了第三个连接,以确保一致性 - 您不应该混合使用旧式和新式ANSI连接语法,它会起作用,但会使查询变得难以阅读。

+0

的'tb_player_last_login'之前应该有'INNER JOIN'或'LEFT OUTER JOIN'在新的左连接中它说“有一个表”p“的条目,但是它不能从这个部分引用的查询。“在p.id = l.lplayer_id上 – 2014-09-29 16:43:58

2

你只需要添加另一join条款:

select p.id, p.nick, p.creation_date 
from tb_player p 
left outer join tb_invoice i on i.player_id = p.id 
left outer join tb_player_last_login tpl on tpl.player_id = p.id --here 
where p.creation_date < now() - '12 months'::interval 
and tpl.last_login_date < now() - '12 months'::interval 
and p.id > 9999 
and (p.email = 'EDITE-SEU-EMAIL' or p.email = 'configure-seu-email') 
and i.id is null 
limit 15000;