mysql 如何按逗号分隔的值将数据拆分为单独的列

cwdobuhd  于 2022-12-17  发布在  Mysql
关注(0)|答案(1)|浏览(192)

我尝试将KnownForTitles列拆分为4个单独的列,但无法使查询正常工作。
我试过使用子字符串和instr来选择逗号前面的结果,你能看出我哪里出错了吗

Select  nameID, name, 
substring_index(group_concat( Titleid order by nameID), ",", 1) KnownForTitles1,
substring(substring_index(group_concat( Titleid order by nameID), ",", 2), instr(substring_index(group_concat( Titleid order by nameID), ",",2)),",")
KnownForTitles2 

from Person
inner join KnownForTitles using (nameid)
inner Join Media using (titleID)
group by nameID
order by nameID

这是我需要的结果格式:

kpbwa7wx

kpbwa7wx1#

您的风格:

with wTable as (
SELECT nameID, name, concat(group_concat( Titleid order by nameID), ",") gc -- Additional coma at the end will ensure you no errors when you will have less than 4 values per nameID
  FROM Person 
  inner join KnownForTitles using (nameid)
  group by nameID, name
)
select nameID, name,
      substring_index(gc, ",", 1) KnownForTitles1,
      replace(substring_index(gc, ",", 2), concat(substring_index(gc, ",", 1), ","), "")  KnownForTitles2,
      replace(substring_index(gc, ",", 3), concat(substring_index(gc, ",", 2), ","), "")  KnownForTitles3,
      replace(substring_index(gc, ",", 4), concat(substring_index(gc, ",", 3), ","), "")  KnownForTitles4
  from wTable;

不过,这一个看起来更干净:

with wTable as (
SELECT nameID, name, Titleid,
       ROW_NUMBER() OVER(PARTITION BY nameID, name order by Titleid) AS rn
  FROM Person 
  inner join KnownForTitles using (nameid)
)
select nameID, name,
       min(case when rn = 1 then Titleid end) as KnownForTitles1,
       min(case when rn = 2 then Titleid end) as KnownForTitles2,
       min(case when rn = 3 then Titleid end) as KnownForTitles3,
       min(case when rn = 4 then Titleid end) as KnownForTitles4
  from wTable
  group by nameID, name;

相关问题