Postgresql从2个表中选择。加入?

时间:2010-04-28 15:31:58

标签: sql postgresql join

我有两个看起来像这样的表:

    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 | 

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 | 

我正在尝试从一个表格中的表格中获取list_id,电话和电子邮件。我正在寻找类似的输出:

list_id |    phone    |             email              
---------+-------------+--------------------------------
       0 |             | jqeron@wqwerweper.com
       0 |             | qwerox@wqwekeeper.com
       0 |             | erreon@fdfdeper.com
       0 |             | sfar@weasdfer.com
       0 |             | rawq@gdfefdgheper.com
       1 | 15555555555 | 
       1 | 15555551806 | 
       1 | 15555555508 | 
       1 | 15055555506 | 
       1 | 15055555558 | 
       1 |             | rfoasdfx@wefdaser.com
       1 |             | radfy@wfdfder.com

我想出了

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

但那不太对。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

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