2014-09-29 51 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;