Вопрос

I have a table that list email addressed for a member and has a boolean is_selected. The idea is that only one should be selected. I am joining the table to itself with a where clause on is_selected. I want to

string_agg(u.email, ',')

to show all the unselected emails in one column/row in a view.

Here is a fiddle.

My problem is that I can't get the view to work in cases where there are no entries that are unselected.

sql fiddle is having issues today so:

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?
Это было полезно?

Решение

SQL Fiddle

If the condition on the right side is put in the where clause you transform the left join into an inner join. Just move it to the join condition:

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;
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top