-1

我需要帮助才能从反馈表中收集数据。

我有像这样的桌子

tbl_parent_child_details

fld_parent_id   fld_parent_name  fld_child_name   fld_class   fld_section
1               Tom              Ray               8          A
2               Dev              angelina         12          B 

tbl_feedback_children

fld_parent_id  fld_quetion_id   fld_ans 
1              1                1
1              2                3
1              3                2
2              1                4
2              2                5
2              3                2

tbl_feedback_admini

fld_parent_id  fld_quetion_id   fld_ans 
1              1                1
1              2                3
1              3                2
2              1                4
2              2                5
2              3                2

现在我的要求是我想要一行中每个父母的数据,例如:

Parent child q1 q2 q3 q4 q5 q6
tom ray 1 3 2 1 3 2
dev angelina 4 5 2 4 5 2

非常感谢任何帮助。

4

1 回答 1

0

这种类型的操作称为 a PIVOT,但 MySQL 没有枢轴函数,因此您可以使用带有CASE语句的聚合函数来复制它。

您的查询将与此类似:

select pc.fld_parent_name,
  pc.fld_child_name,
  max(case when a.fld_quetion_id = 1 then a.fld_ans end) q1,
  max(case when a.fld_quetion_id = 2 then a.fld_ans end) q2,
  max(case when a.fld_quetion_id = 3 then a.fld_ans end) q3
from tbl_parent_child_details pc
left join tbl_feedback_admini a
  on pc.fld_parent_id = a.fld_parent_id
left join tbl_feedback_children c
  on pc.fld_parent_id = c.fld_parent_id
  and a.fld_quetion_id = c.fld_quetion_id
group by pc.fld_parent_name, pc.fld_child_name

请参阅SQL Fiddle with Demo

如果您有已知数量的要转换的问题,上述方法效果很好。如果您有未知号码,那么您可以使用类似于以下的准备好的语句:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'max(case when a.fld_quetion_id = ''',
      fld_quetion_id,
      ''' then a.fld_ans end) AS q',
      fld_quetion_id
    )
  ) INTO @sql
FROM tbl_feedback_admini;

SET @sql = CONCAT('SELECT pc.fld_parent_name, 
                    pc.fld_child_name, ', @sql, ' 
                  from tbl_parent_child_details pc
                  left join tbl_feedback_admini a
                    on pc.fld_parent_id = a.fld_parent_id
                  left join tbl_feedback_children c
                    on pc.fld_parent_id = c.fld_parent_id
                    and a.fld_quetion_id = c.fld_quetion_id
                  group by pc.fld_parent_name, pc.fld_child_name');

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

请参阅带有演示的 SQL Fiddle

两者都将返回结果:

| FLD_PARENT_NAME | FLD_CHILD_NAME | Q1 | Q2 | Q3 |
---------------------------------------------------
|             Dev |       angelina |  4 |  5 |  2 |
|             Tom |            Ray |  1 |  3 |  2 |
于 2012-12-16T21:17:53.323 回答