mysql - join 2 tables using a pivot -
can please me this...
so have 2 tables.
user_info(username,firstname,lastname,address) , user_contact(username,number,primary,alternate)
example fields in 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)
('def',xxx-xxx-xxxx,0,1)
this means user can have more 1 alternate phone numbers.
what want join 2 tables, , result like,
(username,primary number, alternate num1, alternate num2, alternate num3 .. )
what have far this, can give me 1 alternate number , not all.
select username,firstname,lastname,address, sum(if(c.primary=1,c.number,null) primary, sum(if(c.alternate=1,c.number,null) alternate user_info left join user_contact c on i.username = c.username group username
i appreciate lot. read pivote tables, im unable find answers doubts.
thanks in adv
thanks tried solve me. figured out answer it. if curious, goes way
select username, firstname,lastname,address, max(if(uc.`primary`=1 , uc.row_num=1, uc.number,0)) phone, max(if(uc.row_num=2, uc.number,0)) alt1, max(if(uc.row_num=3, uc.number,0)) alt2, max(if(uc.row_num=4, uc.number,0)) alt3, max(if(uc.row_num=5, uc.number,0)) alt4 user_info ui left join ( select username, number,`primary`,alternate, if(@type = username,@rownum:=@rownum+1,@rownum:=1) row_num, @type := username `type` user_contact , (select @rownum:=0 , @type:='') r group username, number order username, `primary` desc ) uc on ui.username = uc.username order username
Comments
Post a Comment