2014-02-05 33 views
1

任何人都可以請這個幫我...使用關鍵點連接2個表格

所以我有兩個表格。

USER_INFO(用戶名,名字,姓氏,地址) AND user_contact(用戶名,號碼,主,備用)在user_contacts

示例字段
( 'ABC',XXX-XXX- ('abc',xxx-xxxx,0,1)
('abc',xxx-xxx-xxxx,0,1)
('abc',xxx-xxx- -xxxx,0,1)
('def',xxx-xxx-xxxx,1,0)
( '高清',XXX-XXX-XXXX,0,1)
( '高清',XXX-XXX-XXXX,0,1)

這意味着用戶可以有多於一個的備用電話數字。

我想要做的是加入了兩個表,而得到的結果一樣,
(用戶名,主號碼,備用NUM1,NUM2交替,交替NUM3 ..)

我有那麼這遠非如此,但這隻能給我一個備用號碼,而不是全部號碼。

select username,firstname,lastname,address, 
     sum(if(c.primary=1,c.number,NULL) as primary, 
     sum(if(c.alternate=1,c.number,NULL) as alternate 
from user_info as i left join 
    user_contact as c 
    on i.username = c.username 
group by username 

我會很感激的幫助。我讀到了轉折表,但我無法找到解答我的疑惑的東西。

謝謝

+0

考慮處理在表示層/應用級代碼數據顯示的問題(如作用於有序陣列一個簡單的PHP環路) – Strawberry

+0

我同意,我就用沒有PHP,但我需要使用MySQL來做到這一點。 – Aman

回答

0

感謝所有試圖爲我解決這個問題的人。 我想出了答案。如果你很好奇,它會這樣

select username, firstname,lastname,address, 
max(if(uc.`primary`=1 AND uc.row_num=1, uc.number,0)) as phone, 
max(if(uc.row_num=2, uc.number,0)) as alt1, 
max(if(uc.row_num=3, uc.number,0)) as alt2, 
max(if(uc.row_num=4, uc.number,0)) as alt3, 
max(if(uc.row_num=5, uc.number,0)) as alt4 
from user_info as ui 
left join 
(
Select username, number,`primary`,alternate, 
    if(@type = username,@rowNum:[email protected]+1,@rowNum:=1) as row_num, 
    @type := username as `type` 
from user_contact , (select @rowNum:=0 , @type:='') as r 
group by username, number 
order by username, `primary` desc 
) as uc 
on ui.username = uc.username 
order by username