0

我有这个,EAV方法:

Forms_data [id | form_id | survey_id | key  | value ]
           [1  | 1       | 1         | q1   |  Male ]
           [2  | 1       | 1         | q2   | 1/1/76]
           [3  | 2       | 1         | Car  |  Honda]
           [4  | 2       | 1         | Eng  | Petrol]
           [5  | 1       | 2         | q1   |  Fem  ]
           [6  | 1       | 2         | q2   | 2/3/81]
           [7  | 2       | 2         | Car  |  Ford ]
           [8  | 2       | 2         | Eng  | Diesel]

然后我想创建视图,例如:

查看表单 ID 1:

[survey_id  |  q1   | q2     ]
[ 1         |  Male | 1/1/76 ] 
[ 2         |  Fem  | 2/3/81 ]

查看表单 ID 2:

[survey_id  |  car   | eng     ]
[ 1         |  Honda | Petrol  ] 
[ 2         |  Ford  | Diesel  ]

我将如何在 MySQL 中执行此操作?

4

1 回答 1

1

不幸的是,MySQL 没有 PIVOT 函数将数据行转换为列,但您可以使用带有 CASE 表达式的聚合函数来获取结果。

如果您key提前知道这些值,则可以对查询进行硬编码:

select survey_id,
  max(case when `key`='q1' then value end) q1,
  max(case when `key`='q2' then value end) q2
from yt
where form_id = 1
group by survey_id;

select survey_id,
  max(case when `key`='car' then value end) car,
  max(case when `key`='eng' then value end) eng
from yt
where form_id = 2
group by survey_id;

请参阅SQL Fiddle with Demo

但是,如果您希望结果是动态的,那么您将需要使用准备好的语句来获得结果:

SET @sql = NULL;
SET @form_id = 1;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'max(CASE WHEN `key` = ''',
      `key`,
      ''' THEN value END) AS `',
      `key`, '`'
    )
  ) INTO @sql
FROM yt
where form_id = @form_id;

SET @sql 
  = CONCAT('SELECT survey_id, ', @sql, ' 
            from yt
            where form_id = ', @form_id, '
            group by survey_id');


PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

请参阅带有演示的 SQL Fiddle

于 2013-06-18T15:52:38.207 回答