【问题标题】:Update the column with Specific Comma Separated Value [duplicate]使用特定的逗号分隔值更新列 [重复]
【发布时间】:2017-06-07 05:50:38
【问题描述】:

我创建了一个以逗号分隔的形式存储值的表。 有没有什么机制可以达到以下效果?

我在表中有名为 qty 的列,它以以下格式存储值:

Initially Column Contain:-  1,5,8,9,7,10,5

现在我想更新第三个值,即 8 x 2

So Final Answer that Column contain is:-  1,5,2,9,7,10,5

【问题讨论】:

  • 这就是为什么我们不将表示值列表的逗号分隔字符串作为列值。 PS 当你用谷歌搜索各种关于你的问题的明确陈述时,你发现了什么?例如你的标题加标签? (尽管您的标题应该更清楚。)这是一个通过简单的谷歌搜索回答的常见问题。回答者应该都将其标记为重复。
  • 编写一个程序来解析字符串并传递位置和替换值的参数。但是您不应该以这种方式存储数据。
  • 我不同意将其标记为重复。上面的两个答案都没有回答提出的问题。认为这是一种不好的数据存储方式的观点不是答案。

标签: mysql sql


【解决方案1】:

您可以使用字符串替换,因为这不是一个格式良好的规范化数据库。

您的数据库应遵循标准规范化模式,以便在性能、可用​​性和维护方面更好的表之间获得稳固的关系。你的表甚至不是 1NF。

虽然这个查询现在有帮助,但请考虑改变你的结构。

   update TBL 
       set column = replace(column , '8', '2') 
     where your_condition

查看此链接以了解有关规范化及其形式的更多信息:Normalization

【讨论】:

  • 关于规范化的好点,对此投了赞成票。
  • 以下情况会失败:update wp_posts set test_csv = '1,2,9,10,101,11,121,1248,8956' where ID = 116;然后更新 wp_posts set test_csv = replace(test_csv,'10', '101') where ID = 116;
【解决方案2】:

假设 Student 表中有 SampleID 列:

表中Name的值为:'1,5,8,9,7,10,5',你想用'2'替换'8'

您可以使用以下查询:

UPDATE dbo.Student
SET [SampleID] = REPLACE([SampleID], '8', '2')

您可以进一步修改它以获得更高的准确性。

【讨论】:

    【解决方案3】:

    使用几个字符串函数可以做到这一点:

    update yourtabel
    set yourcol = 
        concat(
            substring_index(yourcol, ',', 2), -- this will get string without trailing comma before third value
            ',',
            '2', -- the value you want to update to third value
            ',',
            substring_index(
                yourcol,
                ',',
                2 - (length(yourcol) - length(replace(yourcol, ',', '')))
            ) -- this will get string without heading comma after third value
         )
    

    这是SQLFiddle 中的演示。

    substring_index:https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_substring-index
    length:https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_length
    替换:https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_replace

    【讨论】:

      【解决方案4】:

      实际上你不应该用逗号存储值,因为这会导致 SQL 注入攻击,并且后面没有 reasons。但是现在处理使用下面的查询:

           update table_name set coulmn_name=REPLACE('1,5,8,9,7,10,5', '8', '2') where 1
       and conditions;
      

      【讨论】:

        猜你喜欢
        • 2019-03-19
        • 1970-01-01
        • 1970-01-01
        • 2014-07-31
        • 2011-07-26
        • 2013-07-05
        • 2011-06-18
        • 1970-01-01
        • 2014-02-19
        相关资源
        最近更新 更多