【问题标题】:Split comma separated value in to multiple rows in mysql [duplicate]在mysql中将逗号分隔值拆分为多行[重复]
【发布时间】:2021-08-31 10:14:56
【问题描述】:

我有一张这样的桌子,考虑一下
表名作为样本

   info | values
  -------------
   1     1,2,4,5
   2     5, 6,7

当我选择信息值为 1 而不是逗号分隔值的示例表时,有什么方法可以拆分该值并将其作为多行返回

    info | values
     1      1
     1      2
     1      4
     1      5 

如果我得到这个,我会将它作为子查询并将其传递给 where in cluase 以从其他表中获取其他数据。

【问题讨论】:

  • 你为什么不用你的服务器端编程语言来做呢?
  • 是的,但这是报告查询,我需要将此值作为输入传递给另一个表 where in 子句 .. 因为它是非常庞大的数据,我们想从 db 中过滤它
  • very huge - 在处理大表时您应该学习如何简化查询。你要求的那个..会使事情复杂化
  • 还有一个原因我是 mysql 的初学者,我很想知道如何编写这个查询
  • 下面给出答案。但我不会根据您的需要推荐已回答的查询作为子查询

标签: mysql sql


【解决方案1】:

如果你知道最大数量,你可以使用一堆union alls。对于您的示例数据,这就足够了:

select col1, substring_index(col2, ',', 1)
from t
union all
select col1, substring(substring_index(col2, ',', 2), ',', -1)
from t
where col2 like '%,%'
union all
select col1, substring(substring_index(col2, ',', 3), ',', -1)
from t
where col2 like '%,%,%'
union all
select col1, substring(substring_index(col2, ',', 4), ',', -1)
from t
where col2 like '%,%,%,%';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-25
    • 1970-01-01
    • 2011-07-26
    • 1970-01-01
    • 2013-10-05
    • 2019-09-11
    • 1970-01-01
    相关资源
    最近更新 更多