我有一个表格,列出了为成员发送的电子邮件,并且有一个布尔值 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?