简体   繁体   English

mysql用另一个替换一个字符

[英]mysql replace a character with another

I have a table with some values like below, 我有一个表格,下面有一些值,

Slno
---------
IFAAA1121
IFAAA1122
IMBBB1121
IMBBB11223

My goal is to reformat the SlNo in to the below format, 我的目标是将SlNo重新格式化为以下格式,

Slno
---------
IF-AAA-1121
IF-AAA-1122
IM-BBB-1121
IM-BBB-11223

How is it possible ? 这怎么可能 ?

My query is: 我的查询是:

UPDATE `certificate_log_uae` 
SET `DeviceSerialNumberTemp` = REPLACE(LEFT(DeviceSerialNumberTemp,2),
                                       LEFT(DeviceSerialNumberTemp,2).'-')

One approach would be to just build the final string you want using concatenation: 一种方法是使用串联构建所需的最终字符串:

UPDATE certificate_log_uae
SET DeviceSerialNumberTemp = CONCAT(LEFT(DeviceSerialNumberTemp, 2),
                                    '-',
                                    SUBSTRING(DeviceSerialNumberTemp, 3, 3),
                                    '-',
                                    SUBSTRING(DeviceSerialNumberTemp, 6));

在此输入图像描述

Demo 演示

If you are using MySQL 8+ or later, then there is a very simple regex based solution using REGEXP_REPLACE : 如果您使用的是MySQL 8+或更高版本,那么使用REGEXP_REPLACE有一个非常简单的基于正则表达式的解决方案:

SELECT
    DeviceSerialNumberTemp,
    REGEXP_REPLACE(DeviceSerialNumberTemp, '(.{2})(.{3})(.*)', '$1-$2-$3') AS output
FROM certificate_log_uae;

Demo 演示

  • You can use the Substr() function to get substrings out from your input string, at various positions and lengths. 您可以使用Substr()函数从输入字符串中获取各种位置和长度的子字符串。
  • Since the length of the last substring is not fixed; 由于最后一个子串的长度不固定; we can simply specify the start position to slice the substring, and leave specifying the length parameter. 我们可以简单地指定切片子串的起始位置,并指定长度参数。 It will consider the substring till the end of the overall string. 它将考虑子串直到整个字符串的结尾。
  • Now, just concatenate this substrings back using - appropriately. 现在,只需使用-适当地连接这个子串。

Try the following: 请尝试以下方法:

UPDATE `certificate_log_uae` 
SET `DeviceSerialNumberTemp` = CONCAT(SUBSTR(`DeviceSerialNumberTemp`, 1, 2), 
                                      '-', 
                                      SUBSTR(`DeviceSerialNumberTemp`, 3, 3), 
                                      '-', 
                                      SUBSTR(`DeviceSerialNumberTemp`, 6)
                                     ) 

Try simple insert function: 尝试简单的insert功能:

select Slno, insert(insert(slno, 3, 0, '-'), 7, 0, '-') from tbl

Demo 演示

To update values try: 要更新值,请尝试:

update certificate_log_uae set
DeviceSerialNumberTemp = insert(insert(DeviceSerialNumberTemp , 3, 0, '-'), 7, 0, '-')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM