postgres聚合不显示LEFT JOIN表具有空值的行

时间:2013-08-13 15:50:13

标签: postgresql null aggregate string-aggregation

我有一个表,列出了为成员发送的电子邮件,并且有一个布尔值is_selected。这个想法是只应该选择一个。我正在使用is_selected的where子句加入表。我想

string_agg(u.email, ',')

显示视图中一列/一行中的所有未选择的电子邮件。

Here is a fiddle

我的问题是,在没有未选中的条目的情况下,我无法使视图工作。

sql fiddle今天有问题所以:

CREATE TABLE member_email
  (
    member integer NOT NULL, -- reference to another table
    email character varying(150) NOT NULL,
    is_selected boolean NOT NULL,
    PRIMARY KEY(member,email)
  );

INSERT INTO member_email 
    (member,email,is_selected) 
    VALUES 
        (2,'dax@example.com',TRUE),
        (2,'oldemail@example.com',FALSE),
        (2,'prevemail@example.com',FALSE),
        (3,'rick@example.com',TRUE),
        (3,'richard@example.com',FALSE),
        (4,'bob@example.com',TRUE);

CREATE VIEW v_member_email AS 
    SELECT s.member
    ,s.email as selected_email
    ,string_agg(u.email, ',') as unselected_email 
    FROM member_email s 
    LEFT JOIN member_email u 
        ON s.member = u.member 
    WHERE s.is_selected = TRUE 
        AND u.is_selected = FALSE 
    GROUP BY s.member,s.email 
    ORDER BY member;

SELECT * FROM v_member_email;

-- where is bob@example.com in result?

1 个答案:

答案 0 :(得分:1)

SQL Fiddle

如果右侧的条件放在where子句中,则会将left join转换为inner join。只需将其移至连接条件:

select
    s.member
    ,s.email as selected_email
    ,string_agg(u.email, ',') as unselected_email 
from
    member_email s 
    left join
    member_email u on
        s.member = u.member
        and not u.is_selected
where s.is_selected
group by s.member,s.email 
order by member;