[英]How to remove leading and trailing whitespace in a MySQL field?
我有一個包含兩個字段(國家和 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 中)遍歷表並查找/替換 field2 中的空格?
您正在尋找TRIM 。
UPDATE FOO set FIELD2 = TRIM(FIELD2);
似乎值得一提的是,TRIM 可以支持多種類型的空格,但一次只能支持一種,並且默認情況下會使用一個空格。 但是,您可以嵌套TRIM
。
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+
我根據您的答案和其他鏈接組成的一般答案對我有用,我在評論中寫道:
UPDATE FOO set FIELD2 = TRIM(Replace(Replace(Replace(FIELD2,'\t',''),'\n',''),'\r',''));
等等。
因為 trim() 不會刪除所有空格,所以最好替換你想要的所有空格而不是修剪它。
希望我能幫助你分享我的答案:)
請在使用此解決方案之前了解用例:
執行選擇查詢時修剪不起作用
這有效
select replace(name , ' ','') from test;
雖然這不
select trim(name) from test;
需要明確的是,默認情況下 TRIM僅刪除空格(並非所有空格)。 這是文檔: http : //dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_trim
似乎當前的答案都不會真正從字符串的開頭和結尾刪除 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
s - 在一般情況下,這可能會無限期地持續下去。
對於輕量級解決方案,應該可以編寫一個簡單的用戶定義函數 (UDF) 來通過循環字符串開頭和結尾的字符來完成這項工作。 但我不會那樣做……因為我已經寫了一個更重量級的正則表達式替換器,它也可以完成這項工作 - 並且可能由於其他原因而有用,如本博文所述。
演示
Rexester 在線演示。 特別是,最后一行顯示其他方法失敗但正則表達式方法成功。
功能:
-- ------------------------------------------------------------------------------------
-- 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;
此語句將刪除和更新數據庫的字段內容
刪除字段值左側的空格
更新表 SET field1 = LTRIM(field1);
前任。 更新成員 SET firstName = LTRIM(firstName);
刪除字段值右側的空格
更新表 SETfield1 = RTRIM(field1);
前任。 更新成員 SET firstName = RTRIM(firstName);
我需要修剪具有名字和姓氏的主鍵列中的值,所以我不想修剪所有空格,因為這會刪除我需要保留的名字和姓氏之間的空格。 對我有用的是...
UPDATE `TABLE` SET `FIELD`= TRIM(FIELD);
要么
UPDATE 'TABLE' SET 'FIELD' = RTRIM(FIELD);
要么
UPDATE 'TABLE' SET 'FIELD' = LTRIM(FIELD);
請注意, FIELD 的第一個實例在單引號中,但第二個實例根本不在引號中。 我必須這樣做,否則它給了我一個語法錯誤,說當我在引號中時,它是一個重復的主鍵。
如果需要在select查詢中使用trim,也可以使用正則表達式
SELECT * FROM table_name WHERE field RLIKE ' * query-string *'
返回帶有“查詢字符串”等字段的行
您可以使用 ltrim 或 rtrim 來清除右側或左側或字符串的空格。
可以使用下面的sql,UPDATE TABLE
SET Column
= replace(Column , ' ','')
我知道它已經被接受了,但是對於像我這樣尋找“刪除所有空格”的人(不僅僅是在字符串的開頭和結尾):
select SUBSTRING_INDEX('1234 243', ' ', 1);
// returns '1234'
編輯 2019/6/20:是的,那不好。 該函數返回字符串的一部分,因為“當字符空間第一次出現時”。 所以,我想說這會刪除前導和尾隨空格並返回第一個單詞:
select SUBSTRING_INDEX(TRIM(' 1234 243'), ' ', 1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.