我有两张桌子。就像
----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
如何在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
答案 0 :(得分:3)
如果总共最多有3列(在这种情况下拥有父亲和母亲),则不必使用数据透视网
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)