mysql - SQL 连接以将主表中的值与子表值连接为一行中的不同列

标签 mysql sql join dynamic-pivot

我有一个 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

但最喜欢的值是在单个字段中获取,我希望它在不同的列中。我该怎么做

最佳答案

您可以通过执行动态 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;

Find a demo here

关于mysql - SQL 连接以将主表中的值与子表值连接为一行中的不同列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47529967/

相关文章:

sql - 如何避免在多个表上的 SQL 上使用笛卡尔积

php - ajax方法发布不起作用

php - mysql中where子句查询多列

mysql - 我如何在 MySQL 中创建一个安全的计数器(我正在寻找一个通用的解决方案)?

mysql - 如何确定表 1 中的主键是否出现在表 2 中

mysql - 如何在 MySQL 更新时合并具有重复唯一键的行

MySQL 连接来自另一个表的计数匹配记录,但我也需要零值

javascript - 如何合并和匹配 2 个单独的对象?

mysql - 最大和计数查询

mysql - 用于查找重复行并返回两个 ID 的 SQL 查询