简体   繁体   中英

MySQL Pivot table Query in dynamic rows

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM