2017-03-03 56 views
1

選擇單行多行我有一個接觸表如下:在連接表

contactid | contactname 
----------|------------- 
C1  | Name1 
C2  | Name2 

我有一個溝通表如下

contactid | communication_type | communication_string 
----------|--------------------|--------------------- 
C1  | Phone    | 9090909090 
C1  | Email    | [email protected] 
C2  | Phone    | 9191919191 
C2  | Email    | [email protected] 

現在,我的要求是查詢這兩個表,使得結果如下:

contactid | contactname | phonenumber | emailaddress 
----------|-------------|---------------|---------------- 
C1  | Name1  | 9090909090 | [email protected] 
C2  | Name2  | 9191919191 | [email protected] 

如果我做了常規連接,如

SELECT cont.contactid, cont.contactname, 
    comm.communication_type, comm.communication_string 
    FROM contact cont 
    LEFT JOIN communication comm ON cont.contactid = comm.contactid 

我會像

contactid | contactname | communication_type| communication_string 
----------|-------------|-------------------|---------------- 
C1  | Name1  | Phone    | 9090909090 
C1  | Name1  | Email    | [email protected] 
C2  | Name2  | Phone    | 9191919191 
C2  | Name2  | Email    | [email protected] 

但這不是我想要的。 我希望結果中的同一行中的通信字符串,而不是不同的行。

這是否可能得到這樣的結果。

還有一個要求是解決方案應該是通用的,可以在所有數據庫上工作。

+0

不要標記每個數據庫傢伙。現在來吧。這是一個關鍵問題,他們都以不同的方式做。 –

回答

2

可以使用條件彙總:

select cont.contactid, 
    cont.contactname, 
    max(case when comm.communication_type = 'Phone' then comm.communication_string end) PhoneNumber, 
    max(case when comm.communication_type = 'Email' then comm.communication_string end) EmailAddress 
from contact cont 
left join communication comm on cont.contactid = comm.contactid 
group by cont.contactid, 
    cont.contactname; 

這將返回一個Phonenumber來和EMAILADDRESS給定的ContactID。

該解決方案將適用於大多數RDBMS。

+0

這對我有效..!謝謝..但是,你是否用max來避免group by子句或其他原因? – Rama

+0

@Rama - 這是一種常見的旋轉技術,即將行轉換爲列。並不是所有的數據庫都支持'PIVOT'子句(mysql就是其中之一)。 – GurV

2

你可以用不同的條件下多次加入相同的表:

select c.contactid 
    ,c.contactname 
    ,cp.comunication_string as 'phonenumber' 
    ,ce.comunication_string as 'emailaddress' 

from contact c 
     left join 
     communication cp on c.contactid = cp.contactid 
          and cp.comunication_type = 'Phone' 
     left join 
     communication ce on c.contactid = ce.contactid 
          and ce.comunication_type = 'Email' 

標準SQL,易於閱讀。