0

我想不通这个。

我有这张桌子:

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

我希望我被理解......

4

1 回答 1

2

您所要求的基本上是 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

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

于 2012-12-05T15:34:14.990 回答