使用数据透视表连接2个表

时间:2014-02-05 22:52:05

标签: mysql join pivot-table

任何人都可以帮助我...

所以我有两张桌子。

USER_INFO (用户名,名字,姓氏,地址) 和 user_contact (用户名,号码,主,备用)

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

这意味着用户可以拥有多个备用电话号码。

我想要做的是加入两个表,得到结果,如, (用户名,主号码,备用号码1,备用号码2,备用号码3 ..)

到目前为止我所拥有的是这个,但是这只能给我一个替代号而不是全部。

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

我会很感激帮助。我读到了枢轴表,但我无法找到能够解答我疑虑的东西。

先谢谢

1 个答案:

答案 0 :(得分: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:=@rowNum+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