php - 动态行中的MySQL数据透视表查询

标签 php mysql

我有两张 table 。就像

----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

最佳答案

如果始终有最多 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)

关于php - 动态行中的MySQL数据透视表查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35462255/

相关文章:

php - 从 Linux 迁移到 Windows 后的 WSOD

php - 如何在 PHP 中格式化来自 MySQL 的时间戳?

php - 如何在下拉 PHP MySQL 中获取选定值?

php - 如何从数组变量PHP中获取指定列到动态变量中

php - 使用 PHP cURL 发送 SMS 文本消息的简单 GET 请求

php - 在 PHP 中将整数舍入到最接近的 5 的倍数

php - 模拟库可以用来创建多个日志文件吗?

php - 查找特定日期/任何年份的所有行

php - 我们可以在 Codeigniter 的单选按钮中传递数组值吗?

php - SQL 无法获取记录