【问题标题】:join 2 tables using a pivot使用数据透视表连接 2 个表
【发布时间】:2014-02-05 22:52:04
【问题描述】:

谁能帮我解决这个问题...

所以我有两张桌子。

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)
('def',xxx-xxx-xxxx,0,1)

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

我想要做的是加入这两个表,并得到类似的结果,
(用户名,主号码,备用 num1,备用 num2,备用 num3 ..)

到目前为止我所拥有的是这个,但这只能给我 1 个备用号码,而不是全部。

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

我将非常感谢您的帮助。我阅读了数据透视表,但找不到能回答我疑问的东西。

感谢广告

【问题讨论】:

  • 考虑处理表示层/应用程序级代码中数据显示的问题(例如,作用于有序数组的简单 PHP 循环)
  • 我同意,我是使用 PHP 完成的,但我需要使用 MySQL 才能这样做。

标签: mysql join pivot-table


【解决方案1】:

感谢所有试图为我解决这个问题的人。 我想出了答案。如果你好奇,那就这样吧

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    • 2017-04-02
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 2018-10-29
    • 1970-01-01
    相关资源
    最近更新 更多