将mysql表文本值拆分为多行

sg24os4d  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(354)

我有一张table:

id | room_type     | room_size
1  | a;b;c         | 5;7;12   
2  | b;c;d;f       | 8;2;4
3  | b;c;d;f;g;h   | 6;4;5;6;7;2;9

我想要这样的输出:

id | name    | room_size
1  | a       | 5
1  | b       | 7
1  | c       | 12
2  | b       | 8
2  | c       | 2
2  | d       | 4
2  | f       | NULL
3  | b       | 6
3  | c       | 4
3  | d       | 5
3  | f       | 6
3  | g       | 7
3  | h       | 2

注:在(id)2中,房间大小计数小于1。在(id)3中,房间大小增加了1

6jjcrrmo

6jjcrrmo1#

不要存储逗号分隔的值列表(这并不意味着用分号代替逗号。)
sql反模式:避免数据库编程的陷阱——bill karwin,第2章
可在亚马逊和其他优秀的书商。
https://www.amazon.com/sql-antipatterns-programming-pragmatic-programmers/dp/1934356557
对于有限数量的值,我们可以将它们拆分为单独的行
(替换内联视图) t 用你的table)

SELECT t.id
     , i.n
     , NULLIF(SUBSTRING_INDEX(SUBSTRING_INDEX(CONCAT( t.room_type ,';;'),';',i.n),';',-1),'') AS room_type_n
     , NULLIF(SUBSTRING_INDEX(SUBSTRING_INDEX(CONCAT( t.room_size ,';;'),';',i.n),';',-1),'') AS room_size_n
  FROM ( SELECT 1 AS id, 'a;b;c' AS room_type, '5;7;12'  AS room_size
         UNION ALL SELECT 2,'b;c;d;f','8;2;4'
         UNION ALL SELECT 3,'b;c;d;f;g;h','6;4;5;6;7;2;9'
       ) t
 CROSS
  JOIN ( SELECT 1 AS n
         UNION ALL SELECT 2
         UNION ALL SELECT 3
         UNION ALL SELECT 4
         UNION ALL SELECT 5
         UNION ALL SELECT 6
         UNION ALL SELECT 7
         UNION ALL SELECT 8
         UNION ALL SELECT 9
       ) i 
HAVING NOT ( room_type_n <=> NULL )
 ORDER BY t.id, i.n

退货:

id    n  room_type_n  room_size_n
---  ---  -----------  -----------
  1    1  a            5
  1    2  b            7
  1    3  c            12
  2    1  b            8
  2    2  c            2
  2    3  d            4
  2    4  f            (NULL)
  3    1  b            6
  3    2  c            4
  3    3  d            5
  3    4  f            6
  3    5  g            7
  3    6  h            2

内联视图 i 应扩展到我们期望提取的有限的最大值数: UNION ALL SELECT 10 UNION ALL SELECT 11 ... .

相关问题