我有一个数据库,在一个名为jos_facileforms_subrecords
的表中有两列。我想报告:记录,价值
记录包含一组唯一记录值,值包含我想要转换为列的值。即:
RECORD | NAME | VALUE
1 | firstname | Frank
1 | lastname | Smith
1 | email | fsmith@email.com
2 | firstname | Sally
2 | lastname | Jones
2 | email | sjones@email.com
3 | firstname | Peter
3 | lastname | Baker
3 | email | pbaker@gmail.com
我想将其转换为每个记录集的一行。即。
FIRST NAME | LAST NAME | EMAIL
Frank | Smith | fsmith@email.com
Sally | Jones | sjones@email.com
Peter | Baker | pbaker@email.com
答案 0 :(得分:0)
您正在寻找的是PIVOT查询。其他DBMS有这方面的功能,遗憾的是MySQL没有,所以你必须手动完成。有几种方法可以实现这一目标。这是适合您情况的一个:
select
f.`record` as `record`,
f.`value` as `first name`,
l.`value` as `last name`,
e.`value` as `email`
from
jos_facileforms_subrecords f
inner join jos_facileforms_subrecords l on f.record = l.record
inner join jos_facileforms_subrecords e on f.record = e.record
where
f.name = 'firstname'
and l.name = 'lastname'
and e.name = 'email'
group by f.`record`
请参阅此fiddle。