views:

35

answers:

1

I have 2 tables that look like this:

    Table "public.phone_lists"
  Column  |       Type        |                             Modifiers                              
----------+-------------------+--------------------------------------------------------------------
 id       | integer           | not null default nextval(('"phone_lists_id_seq"'::text)::regclass)
 list_id  | integer           | not null
 sequence | integer           | not null
 phone    | character varying | 
 name     | character varying | 

and

Table "public.email_lists"
 Column  |       Type        |                             Modifiers                              
---------+-------------------+--------------------------------------------------------------------
 id      | integer           | not null default nextval(('"email_lists_id_seq"'::text)::regclass)
 list_id | integer           | not null
 email   | character varying | 

I'm trying to get the list_id, phone, and emails out of the tables in one table. I'm looking for an output like:

list_id |    phone    |             email              
---------+-------------+--------------------------------
       0 |             | [email protected]
       0 |             | [email protected]
       0 |             | [email protected]
       0 |             | [email protected]
       0 |             | [email protected]
       1 | 15555555555 | 
       1 | 15555551806 | 
       1 | 15555555508 | 
       1 | 15055555506 | 
       1 | 15055555558 | 
       1 |             | [email protected]
       1 |             | [email protected]

I've come up with

select pl.list_id, pl.phone, el.email from phone_lists as pl left join email_lists as el using (list_id);

but thats not quite right. Any suggestions?

+1  A: 
SELECT  list_id, phone, email
FROM    (
        SELECT  list_id, NULL AS phone, email, 1 AS set_id
        FROM    email_lists
        UNION ALL
        SELECT  list_id, phone, NULL AS email, 2 AS set_id
        FROM    phone_lists
        ) q
ORDER BY
        list_id, set_id
Quassnoi
could you be so kind as to explain how this works, and it does work. Thanks.
Daniel
@Daniel: `UNION ALL` is a multiset addition operation, it concatenates two recordsets together. Then the result of the concatenation is ordered by list id, then by source
Quassnoi