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

标签 mysql field removing-whitespace

我有一个包含两个字段(国家和 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 中的空格?

最佳答案

您正在寻找 TRIM .

UPDATE FOO set FIELD2 = TRIM(FIELD2);

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

 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+

关于mysql - 如何删除 MySQL 字段中的前导和尾随空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6858143/

相关文章:

mysql - 如何计算最近一年的 MySQL 中具有旧值的表?

php - 为 octobercms 构建 Eloquent 查询 ownsTo

c++ - 如何设计具有 "annotated"字段的类?

regex - 删除 PostgreSQL 中的所有 Unicode 空格分隔符?

C MySQL 客户端库行为

php - 外键、连接和返回索引

python - 如何更新 Django 的 FileField 实例的文件名?

python-如何计算矢量场的等势线?

html - 如何从给定类的跨度末尾删除?

python - 我将如何消除间距,换行符为我的列表 python 中的每个字符串都有一个空格分隔的字符串