dongluolie3487 2016-02-17 16:23
浏览 53
已采纳

MySQL Pivot表在动态行中查询

I have two tables. Just like

----UserTable---- 
id  user    email       
1   admin   admin@gmail.com
2   editor  editor@gmail.com

----NameTable---- 
name    userid  fullname    mobile
own         1   Rahim       012314
father      1   Karim       120120
mother      1   Florin      212021
own         2   Masum       012314
father      2   Nahid       120120
mother      2   Zane        212021

How to fetch data all (Just Like name, Father, Mother, Own name) data in single query in mysql?

----Output Table----
id  user    email               name        fathername  mothername
1   admin   admin@gmail.com     Rahim       Karim       Florin
2   editor  editor@gmail.com    Masum       Nahid       Zane
  • 写回答

1条回答 默认 最新

  • duan4523 2016-02-17 16:29
    关注

    You dont have to use pivot in case there are always maximum of 3 columns(own,father and mother in this case)

    SELECT t.id,t.user,t.email,
           max(case when s.name = 'own' then s.fullname end) as name,
           max(case when s.name = 'father' then s.fullname end) as fathername,
           max(case when s.name = 'mother' then s.fullname end) as mothername
    FROM UserTable t
    INNER JOIN NameTable s ON(t.id = s.user_id)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮