4

我有一个survey_datas 表包含这样的数据

survey_data_id  | title
1               | Paul 
3               | Anna 
4               | Alan 

另一个表 project_playlist_indexes 包含这样的数据

survey_id  |survey_data_id  | favorite
1          | 1              | 22.10
2          | 1              | 24.00
3          | 3              | 12.00

我想将survey_datas 表与project_playlist_indexes 表连接起来,以便project_playlist_indexes 表中包含的值与survey_datas 表具有相同的survey_data_id 应该得到最喜欢的时间1,最喜欢的时间2,...最喜欢的时间n,我想得到的结果表是像这样

survey_data_id  |title | favorite_time1 | favorite_time2
            1   | paul | 22.10          |24.00
            3   | anna | 12.00          | null
            4   | alan | null           | null

目前我正在使用查询

SELECT s.*,GROUP_CONCAT(pi.favorite) ,pi.*
FROM survey_datas s
LEFT JOIN  project_playlist_indexes pi 
ON pi.survey_data_id = s.survey_data_id  
GROUP BY pi.survey_data_id

但最喜欢的值是在一个字段中,我希望它位于不同的列中。我怎样才能做到这一点

4

1 回答 1

1

您可以通过执行动态 sql 查询来做到这一点。我所做的是,首先根据survey_data_id列给出一个行号。然后选择每个行号项目作为每个列分组survey_data_id。不知道代码效率如何。

询问

set @query = null;
select
  group_concat(distinct
    concat(
      'max(case when `rn` = ',
      `rn`,
      ' then `favorite` end) as `favorite', `rn` , '`'
    )
  ) into @query
from (
  select `survey_id`, `survey_data_id`, `favorite`, (
    case `survey_data_id` when @curA 
    then @curRow := @curRow + 1 
    else @curRow := 1 and @curA := `survey_data_id` end 
  ) as `rn`
  from `project_playlist_indexes` t, 
  (select @curRow := 0, @curA := '') r 
  order by `survey_data_id`, `survey_data_id`
) t;

set @query = concat('select t2.`survey_data_id`, t2.`title`,', 
                @query,
              ' from (select `survey_id`, `survey_data_id`, `favorite`, (
              case `survey_data_id` when @curA 
              then @curRow := @curRow + 1 
              else @curRow := 1 and @curA := `survey_data_id` end 
              ) as `rn`
              from `project_playlist_indexes` t, 
              (select @curRow := 0, @curA := '''') r 
              order by `survey_data_id`, `survey_data_id`) t1
              right join `survey_datas` t2
              on t1.survey_data_id = t2.`survey_data_id`
              group by t1.`survey_data_id`
              order by t2.`survey_data_id`;'
     );

prepare stmt from @query;
execute stmt;
deallocate prepare stmt;

在此处查找演示

于 2017-11-28T11:54:55.797 回答