在SELECT语句上连接表

时间:2017-02-22 13:52:07

标签: sql postgresql

我该如何使这项工作?我有一个表u_uzivatele,我想在表b_objednavky上加入它,但我也不希望加入表u_uzivatele中的行,这些行可以加入表bw_paid_orders 1}}并且不符合WHERE条款。现在,SELECT语句返回表,其中包含表uzivatele中的行,这些行也在表bw_paid_orders中,并满足WHERE子句的条件。但是我无法在表u_uzivatele上加入它,因为返回了多行。

SELECT STMT

FROM b_objednavky INNER JOIN u_uzivatele ON b_objednavky.uzivatel = 
( 
       SELECT u_uzivatele.id 
       FROM   u_uzivatele 
       JOIN   bw_paid_orders 
       ON     u_uzivatele.id = bw_paid_orders.user_id 
       WHERE  bw_paid_orders.active_thru < now() + interval '6 months' ) uzivatele

1 个答案:

答案 0 :(得分:2)

您希望仅u_uzivatele加入不存在某个条目的bw_paid_orders条记录。因此,请使用NOT EXISTS或更简单的NOT IN

select ...
from b_objednavky o
join u_uzivatele u on  u.id = o.uzivatel
                   and u.id not in (select user_id from bw_paid_orders po 
                                    where active_thru < now() + interval '6 months')