如何删除mysql字段中的前导和尾随空格?

qnakjoqk  于 2021-06-21  发布在  Mysql
关注(0)|答案(11)|浏览(440)

我有一个包含两个字段(国家和iso代码)的表:

Table1

   field1 - e.g. 'Afghanistan' (without quotes)
   field2 - e.g. 'AF'(without quotes)

在某些行中,第二个字段的开始和/或结束处有空格,这会影响查询。

Table1

   field1 - e.g. 'Afghanistan' (without quotes) 
   field2 - e.g. ' AF' (without quotes but with that space in front)

有没有方法(在sql中)遍历表并查找/替换字段2中的空白?

utugiqy6

utugiqy61#

我需要修剪主键列中具有名字和姓氏的值,因此我不想修剪所有空白,因为这样会删除名字和姓氏之间的空格,我需要保留这些空格。对我有效的是。。。

UPDATE `TABLE` SET `FIELD`= TRIM(FIELD);

UPDATE 'TABLE' SET 'FIELD' = RTRIM(FIELD);

UPDATE 'TABLE' SET 'FIELD' = LTRIM(FIELD);

请注意,字段的第一个示例是单引号,但第二个示例根本不在引号中。我必须这样做,否则它会给我一个语法错误,说这是一个重复的主键时,我都在引号里。

wgx48brx

wgx48brx2#

目前的答案似乎没有一个能从字符串的开头和结尾去除100%的空白。
如其他帖子所述,默认 TRIM 只删除空格-而不是制表符,窗体提要等。组合 TRIM 指定其他空白字符可能会提供有限的改进,例如。 TRIM(BOTH '\r' FROM TRIM(BOTH '\n' FROM TRIM(BOTH '\f' FROM TRIM(BOTH '\t' FROM TRIM(txt))))) . 但这种方法的问题是,只能为特定的字符指定一个字符 TRIM 这些字符只从开头和结尾删除。所以如果要修剪的绳子 \t \t \t \t (即替换空格和制表符),更多 TRIM 在一般情况下,这种情况可能会无限期地持续下去。
对于轻量级的解决方案,应该可以编写一个简单的用户定义函数(udf),通过循环遍历字符串开头和结尾的字符来完成这项工作。但我不会那么做。。。正如我已经写了一个更重的正则表达式替换程序,它也可以完成这项工作,并且可能会因为其他原因而有用,如本文所述。
演示
rextester在线演示。特别是,最后一行显示其他方法失败,而正则表达式方法成功。
功能:

-- ------------------------------------------------------------------------------------
-- USAGE
-- ------------------------------------------------------------------------------------
-- SELECT reg_replace(<subject>,
--                    <pattern>,
--                    <replacement>,
--                    <greedy>,
--                    <minMatchLen>,
--                    <maxMatchLen>);
-- where:
-- <subject> is the string to look in for doing the replacements
-- <pattern> is the regular expression to match against
-- <replacement> is the replacement string
-- <greedy> is TRUE for greedy matching or FALSE for non-greedy matching
-- <minMatchLen> specifies the minimum match length
-- <maxMatchLen> specifies the maximum match length
-- (minMatchLen and maxMatchLen are used to improve efficiency but are
--  optional and can be set to 0 or NULL if not known/required)
-- Example:
-- SELECT reg_replace(txt, '^[Tt][^ ]* ', 'a', TRUE, 2, 0) FROM tbl;
DROP FUNCTION IF EXISTS reg_replace;
CREATE FUNCTION reg_replace(subject VARCHAR(21845), pattern VARCHAR(21845),
  replacement VARCHAR(21845), greedy BOOLEAN, minMatchLen INT, maxMatchLen INT)
RETURNS VARCHAR(21845) DETERMINISTIC BEGIN 
  DECLARE result, subStr, usePattern VARCHAR(21845); 
  DECLARE startPos, prevStartPos, startInc, len, lenInc INT;
  IF subject REGEXP pattern THEN
    SET result = '';
    -- Sanitize input parameter values
    SET minMatchLen = IF(minMatchLen < 1, 1, minMatchLen);
    SET maxMatchLen = IF(maxMatchLen < 1 OR maxMatchLen > CHAR_LENGTH(subject),
                         CHAR_LENGTH(subject), maxMatchLen);
    -- Set the pattern to use to match an entire string rather than part of a string
    SET usePattern = IF (LEFT(pattern, 1) = '^', pattern, CONCAT('^', pattern));
    SET usePattern = IF (RIGHT(pattern, 1) = '$', usePattern, CONCAT(usePattern, '$'));
    -- Set start position to 1 if pattern starts with ^ or doesn't end with $.
    IF LEFT(pattern, 1) = '^' OR RIGHT(pattern, 1) <> '$' THEN
      SET startPos = 1, startInc = 1;
    -- Otherwise (i.e. pattern ends with $ but doesn't start with ^): Set start position
    -- to the min or max match length from the end (depending on "greedy" flag).
    ELSEIF greedy THEN
      SET startPos = CHAR_LENGTH(subject) - maxMatchLen + 1, startInc = 1;
    ELSE
      SET startPos = CHAR_LENGTH(subject) - minMatchLen + 1, startInc = -1;
    END IF;
    WHILE startPos >= 1 AND startPos <= CHAR_LENGTH(subject)
      AND startPos + minMatchLen - 1 <= CHAR_LENGTH(subject)
      AND !(LEFT(pattern, 1) = '^' AND startPos <> 1)
      AND !(RIGHT(pattern, 1) = '$'
            AND startPos + maxMatchLen - 1 < CHAR_LENGTH(subject)) DO
      -- Set start length to maximum if matching greedily or pattern ends with $.
      -- Otherwise set starting length to the minimum match length.
      IF greedy OR RIGHT(pattern, 1) = '$' THEN
        SET len = LEAST(CHAR_LENGTH(subject) - startPos + 1, maxMatchLen), lenInc = -1;
      ELSE
        SET len = minMatchLen, lenInc = 1;
      END IF;
      SET prevStartPos = startPos;
      lenLoop: WHILE len >= 1 AND len <= maxMatchLen
                 AND startPos + len - 1 <= CHAR_LENGTH(subject)
                 AND !(RIGHT(pattern, 1) = '$' 
                       AND startPos + len - 1 <> CHAR_LENGTH(subject)) DO
        SET subStr = SUBSTRING(subject, startPos, len);
        IF subStr REGEXP usePattern THEN
          SET result = IF(startInc = 1,
                          CONCAT(result, replacement), CONCAT(replacement, result));
          SET startPos = startPos + startInc * len;
          LEAVE lenLoop;
        END IF;
        SET len = len + lenInc;
      END WHILE;
      IF (startPos = prevStartPos) THEN
        SET result = IF(startInc = 1, CONCAT(result, SUBSTRING(subject, startPos, 1)),
                        CONCAT(SUBSTRING(subject, startPos, 1), result));
        SET startPos = startPos + startInc;
      END IF;
    END WHILE;
    IF startInc = 1 AND startPos <= CHAR_LENGTH(subject) THEN
      SET result = CONCAT(result, RIGHT(subject, CHAR_LENGTH(subject) + 1 - startPos));
    ELSEIF startInc = -1 AND startPos >= 1 THEN
      SET result = CONCAT(LEFT(subject, startPos), result);
    END IF;
  ELSE
    SET result = subject;
  END IF;
  RETURN result;
END;

DROP FUNCTION IF EXISTS format_result;
CREATE FUNCTION format_result(result VARCHAR(21845))
RETURNS VARCHAR(21845) DETERMINISTIC BEGIN
  RETURN CONCAT(CONCAT('|', REPLACE(REPLACE(REPLACE(REPLACE(result, '\t', '\\t'), CHAR(12), '\\f'), '\r', '\\r'), '\n', '\\n')), '|');
END;

DROP TABLE IF EXISTS tbl;
CREATE TABLE tbl
AS
SELECT 'Afghanistan' AS txt
UNION ALL
SELECT ' AF' AS txt
UNION ALL
SELECT ' Cayman Islands  ' AS txt
UNION ALL
SELECT CONCAT(CONCAT(CONCAT('\t \t ', CHAR(12)), ' \r\n\t British Virgin Islands \t \t  ', CHAR(12)), ' \r\n') AS txt;     

SELECT format_result(txt) AS txt,
       format_result(TRIM(txt)) AS trim,
       format_result(TRIM(BOTH '\r' FROM TRIM(BOTH '\n' FROM TRIM(BOTH '\f' FROM TRIM(BOTH '\t' FROM TRIM(txt))))))
         AS `trim spaces, tabs, formfeeds and line endings`,
       format_result(reg_replace(reg_replace(txt, '^[[:space:]]+', '', TRUE, 1, 0), '[[:space:]]+$', '', TRUE, 1, 0))
         AS `reg_replace`
FROM tbl;

用法:

SELECT reg_replace(
         reg_replace(txt,
                     '^[[:space:]]+',
                     '',
                     TRUE,
                     1,
                     0),
         '[[:space:]]+$',
         '',
         TRUE,
         1,
         0) AS `trimmed txt`
FROM tbl;
ef1yzkbh

ef1yzkbh3#

我从你的答案和其他链接中得出了一个一般性的答案,我在评论中写道:

UPDATE FOO set FIELD2 = TRIM(Replace(Replace(Replace(FIELD2,'\t',''),'\n',''),'\r',''));

等。
因为trim()不会删除所有的空格,所以最好替换所有需要的空格,而不是修剪它。
希望我能帮你分享我的答案:)

0wi1tuuw

0wi1tuuw4#

如果需要在select查询中使用trim,还可以使用正则表达式

SELECT * FROM table_name WHERE field RLIKE ' * query-string *'

返回字段为'      查询字符串   '

t40tm48m

t40tm48m5#

此语句将删除并更新数据库的字段内容
删除字段值左侧的空白
更新表集合field1=ltrim(field1);
例如,update member set firstname=ltrim(名字);
删除字段值右侧的空白
更新表setfield1=rtrim(field1);
例如,update member set firstname=rtrim(名字);

pxq42qpu

pxq42qpu6#

为了清楚起见,trim在默认情况下只删除空格(不是所有空格)。这是医生:http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_trim

mm5n2pyu

mm5n2pyu7#

我知道它已经被接受了,但是对于像我这样寻找“删除所有空白”的人(不仅仅是在字符串的开头和结尾):

select SUBSTRING_INDEX('1234 243', ' ', 1);
// returns '1234'

编辑2019/6/20:是的,那不好。函数返回自“首次出现字符空间时”起的字符串部分。所以,我猜这样做会删除前导和尾随空格,并返回第一个单词:

select SUBSTRING_INDEX(TRIM(' 1234 243'), ' ', 1);
sqyvllje

sqyvllje8#

您可以使用以下sql,update TABLEColumn =替换(列“”,“”)

p4rjhz4m

p4rjhz4m9#

可以使用ltrim或rtrim清除右、左或字符串的空白。

sbdsn5lh

sbdsn5lh10#

在使用此解决方案之前,请先了解用例:
执行选择查询时修剪不起作用
这很管用

select replace(name , ' ','') from test;

但这并不意味着

select trim(name) from test;
ss2ws0br

ss2ws0br11#

你在找修剪。

UPDATE FOO set FIELD2 = TRIM(FIELD2);

似乎值得一提的是,trim可以支持多种类型的空格,但一次只能支持一种类型,而且默认情况下会使用空格。但是,你可以筑巢 TRIM s。

TRIM(BOTH ' ' FROM TRIM(BOTH '\n' FROM column))

如果你真的想在一次通话中消除所有的空白,最好使用 REGEXP_REPLACE 以及 [[:space:]] 符号。举个例子:

SELECT 
    -- using concat to show that the whitespace is actually removed.
    CONCAT(
         '+', 
         REGEXP_REPLACE(
             '    ha ppy    ', 
             -- This regexp matches 1 or more spaces at the beginning with ^[[:space:]]+
             -- And 1 or more spaces at the end with [[:space:]]+$
             -- By grouping them with `()` and splitting them with the `|`
             -- we match all of the expected values.
             '(^[[:space:]]+|[[:space:]]+$)', 

             -- Replace the above with nothing
             ''
         ), 
         '+') 
    as my_example;
-- outputs +ha ppy+

相关问题