簡體   English   中英

SQL聯接將主表中的值與子表值作為單個行中的不同列進行聯接

[英]SQL join to join values in primary table with child table values as different columns in a single row

我有一個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;

在此處找到演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM