2010-04-28 113 views
1

我有2個表看起來像這樣:Postgesql從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 |    | [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] 

我拿出

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

但是那並不完全正確。有什麼建議麼?

+0

你能解釋爲什麼一些電子郵件沒有list_id嗎? – 2010-04-28 15:35:04

+0

您提供了輸出,但沒有輸入,請提供一個。此外,兩個表中的'list_id'都是'NOT NULL',但你期望在你的輸出中有'NULL'。 – Quassnoi 2010-04-28 15:37:26

+0

那些應該和確實有一個0的list_id,但格式化搞砸了。我會解決這個問題。 – Daniel 2010-04-28 15:38:11

回答

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 
+0

你可以這樣解釋這是如何工作的,它確實有效。謝謝。 – Daniel 2010-04-28 15:45:39

+1

@Daniel:'UNION ALL'是一個多重加法操作,它將兩個記錄集合在一起。然後,連接的結果按列表ID排序,然後按源排序 – Quassnoi 2010-04-28 16:05:04