【问题标题】:Postgresql select from 2 tables. Joins?Postgresql 从 2 个表中选择。加入?
【发布时间】:2010-04-28 15:31:58
【问题描述】:

我有 2 个如下所示的表:

    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);

但这并不完全正确。有什么建议吗?

【问题讨论】:

  • 您能解释一下为什么有些电子邮件没有 list_id 吗?
  • 您提供了输出但没有输入,请提供一个。此外,list_id 在两个表中都是 NOT NULL,但您希望在输出中出现 NULLs
  • 那些应该而且确实有一个 0 的 list_id,但格式搞砸了。我会解决的。

标签: sql postgresql join


【解决方案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

【讨论】:

  • 您能否解释一下这是如何工作的,并且确实有效。谢谢。
  • @Daniel:UNION ALL 是一个多集加法运算,它将两个记录集连接在一起。然后拼接的结果先按list id排序,再按source排序
猜你喜欢
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
  • 2012-04-21
  • 1970-01-01
  • 2018-08-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多