且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-02-24 22:43:03

您正在寻找 TRIM.

UPDATE FOO set FIELD2 = TRIM(FIELD2);


似乎值得一提的是,TRIM 可以支持多种类型的空格,但一次只能支持一种,并且默认情况下会使用一个空格.但是,您可以嵌套 TRIMs.

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

如果你真的想在一次调用中去掉所有的空格,你***使用 REGEXP_REPLACE[[:space:]] 符号.下面是一个例子:

If you really want to get rid of all the whitespace in one call, you're better off using REGEXP_REPLACE along with the [[:space:]] notation. Here is an example:

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+