MySQL的 - 做一个记录了列(MySQL - Make one record out of a

2019-10-30 18:57发布

我不知道这一个了。

我有这个表:

id    component_id     data
1     1                tests@dsaasd.com
1     2                firstname1
1     3                lastname1
1     4                phone1
2     1                email2
2     2                firstname2
2     3                lastname2
2     4                phone2

现在,我想有一个查询,将根据ID中提取全部数据。 我想有这些记录:

1  tests@dsaasd.com  firstname1  lastname1  phone1
2  email2  firstname2  lastname2  phone2

我希望我理解....

Answer 1:

你所要求的基本上是PIVOT但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拨弄演示

其结果是:

| 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拨弄演示

如果你有一个未知的数值,那么你可以使用准备好的语句来动态生成这个查询:

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拨弄演示

所有版本会给你同样的结果。



文章来源: MySQL - Make one record out of a column
标签: mysql sql pivot