我有一个系统,其中有动态用户信息。基本上我有一个用户表,其中包含 ID、姓名、电子邮件和密码(所需的基础知识)。如果系统管理员想要添加用户字段,他们可以通过在 user_fields 表中添加新条目来实现,然后该字段的数据将存储在 user_fields_data 中。
用户:
id | name | email | password
=============================================
1 | bob smith | bob@gmail.com | asdfasdfasdf
...
用户字段:
id | field
==========
1 | address_1
2 | address_2
...
用户字段数据:
user_id | field_id | value
===============================
1 | 1 | 123 abc st
1 | 2 | suite 314
基本上,我的目标是执行单个查询,在其中可以获得所有信息。
array(
'name' => 'bob',
'email' => 'bob@gmail.com',
'password' => 'asdfasdfasdf',
'address_1' => '123 abc st',
'address_2' => 'suite 314'
)
我整天将表格连接在一起,但是我从来没有以这种方式连接表格(行/列)。
提前致谢!
最佳答案
select 'name' as name, name as value from user where id = 1
union all
select 'email', email from user where id = 1
union all
select 'password', password from user where id = 1
union all
select uf.field, ufd.value
from user_fields_data ufd
inner join user_fields uf on ufd.field_id = uf.id
where ufd.user_id = 1
输出:
| NAME | VALUE |
-----------------------------
| name | bob smith |
| email | bob@gmail.com |
| password | asdfasdfasdf |
| address_1 | 123 abc st |
| address_2 | suite 314 |
关于php - MySQL 行与列的联合/连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12287922/