您所要求的基本上是 aPIVOT
但 MySQL 没有数据透视函数,因此您可以使用CASE
带有聚合函数的语句来复制它。
如果您知道这些值,那么您可以对类似于以下的解决方案进行硬编码:
select id,
max(case when component_id = 1 then data end) Email,
max(case when component_id = 2 then data end) Firstname,
max(case when component_id = 3 then data end) Lastname,
max(case when component_id = 4 then data end) Phone
from yourtable
group by id;
请参阅带有演示的 SQL Fiddle
结果是:
| ID | EMAIL | FIRSTNAME | LASTNAME | PHONE |
-----------------------------------------------------------
| 1 | tests@dsaasd.com | firstname1 | lastname1 | phone1 |
| 2 | email2 | firstname2 | lastname2 | phone2 |
我猜你有一个表将 component_id 与名称相关联,所以你的查询也可能是:
select t1.id,
max(case when t2.name = 'email' then data end) Email,
max(case when t2.name= 'FirstName' then data end) Firstname,
max(case when t2.name= 'LastName' then data end) Lastname,
max(case when t2.name= 'phone' then data end) Phone
from yourtable t1
inner join component t2
on t1.component_id = t2.id
group by t1.id;
请参阅带有演示的 SQL Fiddle
如果您有未知数量的值,则可以使用准备好的语句动态生成此查询:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'max(case when name = ''',
name,
''' then data end) AS ',
name
)
) INTO @sql
FROM component;
SET @sql = CONCAT('SELECT t1.id, ', @sql, '
from yourtable t1
inner join component t2
on t1.component_id = t2.id
group by t1.id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
请参阅带有演示的 SQL Fiddle
所有版本都会给你相同的结果。