【问题标题】:How to remove comma separated string of records in MySQL?如何在 MySQL 中删除逗号分隔的记录字符串?
【发布时间】:2016-12-01 20:08:04
【问题描述】:

如何删除逗号分隔的字符串“0000-00-00”

  ID      Name   Return Date
   1       A     0000-00-00,2016-02-1,2016-1-15
   2       B     0000-00-00,2016-04-1
   3       c     0000-00-00,2016-04-4

期待答案

  ID      Name   Return Date
   1       A     2016-02-1,2016-1-15
   2       B     2016-04-1
   3       c     2016-04-4

【问题讨论】:

  • 它们是字符串。您使用标准字符串操作/函数:dev.mysql.com/doc/refman/5.7/en/string-functions.html 如果您的数据库已正确规范化,您就不需要问这个问题。这将是一个简单的delete .. .where date='0000-00-00' 查询。
  • SUBSTRING(`Return Date` FROM 11);
  • 这里真正的解决方案是不要在单个列中存储多个值!

标签: mysql select split trim


【解决方案1】:

认为你有 3 个案例:0000-00-00string 在左、右和中间:

+------+------+--------------------------------+
| ID   | Name | Return Date                    |
+------+------+--------------------------------+
|    1 | A    | 0000-00-00,2016-02-1,2016-1-15 |
|    2 | B    | 0000-00-00,2016-04-1           |
|    3 | C    | 0000-00-00,2016-04-4           |
+------+------+--------------------------------+

使用REPLACE函数:

SELECT `Return Date`, REPLACE(`Return Date`,'0000-00-00,','') as replaced
FROM YourTable;

+--------------------------------+----------------------+
| Return Date                    | replaced             |
+--------------------------------+----------------------+
| 0000-00-00,2016-02-1,2016-1-15 | 2016-02-1,2016-1-15  |
| 0000-00-00,2016-04-1           | 2016-04-1            |
| 0000-00-00,2016-04-4           | 2016-04-4            |
+--------------------------------+----------------------+

你的更新语句是:

UPDATE YourTable
SET `Return Date` = REPLACE(`Return Date`,'0000-00-00,','') 
WHERE `Return Date` like '%0000-00-00,%';

您必须对其他情况进行类似的查询,例如中间或右侧的'0000-00-00'

【讨论】:

    【解决方案2】:

    你也可以试试这个来替换任何其他位置的值:

    Values may be:
    +------------------------------+
    0000-00-00,2016-02-1,2016-1-15 
    2016-02-1,0000-00-00,2016-1-15 
    2016-02-1,2016-1-15,0000-00-00
    0000-00-00
    +------------------------------+
    
    UPDATE YourTable
    SET `Return Date` = TRIM(BOTH ',' FROM
          REPLACE(
            REPLACE(CONCAT(',',REPLACE(`Return Date`, ',', ',,'), ','),',0000-00-00,', ''), ',,', ',')
        )
    WHERE FIND_IN_SET('0000-00-00', `Return Date`)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-14
      • 2012-10-30
      • 1970-01-01
      • 2016-09-04
      相关资源
      最近更新 更多