1

我有一个表格,列出了为成员发送的电子邮件,并且有一个布尔值 is_selected。这个想法是应该只选择一个。我使用 is_selected 上的 where 子句将表连接到自身。我想要

string_agg(u.email, ',')

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

这是一个小提琴

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

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?
4

1 回答 1

1

SQL小提琴

如果右侧的条件放在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;
于 2013-08-13T16:05:54.683 回答