mysql - 遍历表并解析列的数据

标签 mysql sql

我有一张 table ,

incassoid  Amount      Details
=========  ======   ===============
   1       1.0000   5||0.4999;7||0.0001;9||0.0500
   2       2.0000   3||1.0000;15||1.0000
   3       1.0000   8||1.0000

在 detail 列中,5||0.4999 表示 5 是一个 productid0.4999 是钱产品有,我需要的是从详细信息部分获取值并将其表示在表中,它需要遍历所有 incassoid,并且对于每个 incassoid,我需要这样的细节,以 incassoid 1 为例,它应该像这样显示它的细节,

incassoid  Productid   productamount   amount  
=========  =========   ============   =========
   1           5          0.4999         1
   1           7          0.0001         1
   1           9          0.0500         1

我正在尝试找到一种解析详细信息部分的方法,但我不确定该怎么做,有人可以帮我解决这个问题吗。

谢谢!!!

最佳答案

我想你有一张产品表

餐 table 用品

  id
------
    3
    5
    7
    8
    9
   15

你可以使用那个请求做你想做的事

select t.incassoid, p.id productid,
       substring_index(substring_index(t.details, concat(p.id, '||'), -1), ';', 1) productamount,
       t.amount
from products p, tablename t
where find_in_set(p.id, (select group_concat(p2.id)
                         from products p2, tablename t2
                         where t2.incassoid = t.incassoid
                           and (t2.details like concat(p2.id, '||%')
                                or t2.details like concat('%;', p2.id, '||%'))))

find_in_set 中的子请求从详细信息中提取产品 ID 列表。 然后,对于(表名的)每个详细信息,find_in_set 过滤器用于加入正确的产品列表。

之后我们只需要详细提取产品的数量。

SQLFiddle:http://sqlfiddle.com/#!9/7dfd4/1/0

关于mysql - 遍历表并解析列的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37131803/

相关文章:

mysql - 连接表值总和的 SQL 查询

php - 使用 preg_matches 进行多数组匹配

mysql - SQL 表别名

sql - Oracle SQL 按字符串聚合字段分组

mysql - 查找等值连接中的计数

mysql - SQL 查询不从时间戳开始返回所有日期

php - "with"中的 Select 语句返回空数组

PHP SQL防止重复用户名: Catching Exception vs Select Query

mysql - 在数据库中设置名称的最佳做法是什么?

mysql - 根据描述对列进行排序