我找不到MySQL的这个问题,所以这里是:
我需要将字符串中的所有双倍或更多空格修剪为1个单独空格。
例如: “敏捷的棕色狐狸” 应该 : “快速布朗福克斯”
函数REPLACE(str,“”,“”)只删除双空格,但是当有更多空格时会留下多个空格...
答案 0 :(得分:17)
最短,最令人惊讶的最快解决方案:
CREATE FUNCTION clean_spaces(str VARCHAR(255)) RETURNS VARCHAR(255)
BEGIN
while instr(str, ' ') > 0 do
set str := replace(str, ' ', ' ');
end while;
return trim(str);
END
答案 1 :(得分:14)
DELIMITER //
DROP FUNCTION IF EXISTS DELETE_DOUBLE_SPACES//
CREATE FUNCTION DELETE_DOUBLE_SPACES ( title VARCHAR(250) )
RETURNS VARCHAR(250) DETERMINISTIC
BEGIN
DECLARE result VARCHAR(250);
SET result = REPLACE( title, ' ', ' ' );
WHILE (result <> title) DO
SET title = result;
SET result = REPLACE( title, ' ', ' ' );
END WHILE;
RETURN result;
END//
DELIMITER ;
SELECT DELETE_DOUBLE_SPACES('a b');
答案 2 :(得分:11)
我知道这个问题是用mysql标记的,但是如果你有幸使用MariaDB,你可以更轻松地做到这一点:
SELECT REGEXP_REPLACE(column, '[[:space:]]+', ' ');
答案 3 :(得分:10)
这个解决方案不是很优雅,但由于你没有其他选择:
UPDATE t1 set str = REPLACE( REPLACE( REPLACE( str, " ", " " ), " ", " " ), " ", " " );
答案 4 :(得分:8)
DELIMITER //
DROP FUNCTION IF EXISTS DELETE_DOUBLE_SPACES//
CREATE FUNCTION DELETE_DOUBLE_SPACES(str VARCHAR(255)) RETURNS VARCHAR(255)
BEGIN
set str = trim(str);
while instr(str, ' ') > 0 do
set str = replace(str, ' ', ' ');
end while;
return str;
END//
DELIMITER ;
SELECT DELETE_DOUBLE_SPACES(" a b ");
答案 5 :(得分:3)
在搜索之后我最终写了一个函数,即
如果存在trim_spaces则删除函数;
delimiter $$
CREATE DEFINER=`root`@`localhost` FUNCTION `trim_spaces`(`dirty_string` text, `trimChar` varchar(1))
RETURNS text
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
declare cnt,len int(11) ;
declare clean_string text;
declare chr,lst varchar(1);
set len=length(dirty_string);
set cnt=1;
set clean_string='';
while cnt <= len do
set chr=right(left(dirty_string,cnt),1);
if chr <> trimChar OR (chr=trimChar AND lst <> trimChar ) then
set clean_string =concat(clean_string,chr);
set lst=chr;
end if;
set cnt=cnt+1;
end while;
return clean_string;
END
$$
delimiter ;
用法:
set @str='------apple--------banana-------------orange---' ;
select trim_spaces( @str,'-')
输出:apple-banana-orange-
参数trimChar
可以通过重复的任何字符来执行,并且您想要删除。
请注意,它会在重复集
中保留第一个字符 欢呼:)答案 6 :(得分:2)
这是一个古老的技巧,不需要正则表达式或复杂的函数。
您可以像这样3次使用替换功能:
REPLACE('This is my long string',' ','<>')
成为:
This<>is<><><><>my<><><>long<><><><>string
然后,将所有出现的'> <'替换为空字符串”,方法是将其包装在另一个替换项中:
REPLACE(
REPLACE('This is my long string',' ','<>'),
'><',''
)
This<>is<>my<>long<>string
然后最后一个替换将'<>'转换回单个空格
REPLACE(
REPLACE(
REPLACE('This is my long string',
' ','<>'),
'><',''),
'<>',' ')
This is my long string
此示例是在MYSQL中创建的(放在SELECT前面),但是可以使用多种语言。
答案 7 :(得分:1)
如果您使用的是PHP ....
try{
$con = new PDO ("mysql:host=localhost;dbname=dbasename","root","");
}
catch(PDOException $e){
echo "error".$e-getMessage();
}
$select = $con->prepare("SELECT * FROM table");
$select->setFetchMode(PDO::FETCH_ASSOC);
$select->execute();
while($data=$select->fetch()){
$id = $data['id'];
$column = $data['column'];
$column = trim(preg_replace('/\s+/',' ', $column)); // remove all extra space
$update = $con->prepare("UPDATE table SET column=:column WHERE id='$id'");
$update->bindParam(':column', $column );
$update->execute();
// echo $column."<br>";
}
答案 8 :(得分:0)
这是一般性的解决方案:来自
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=56195&whichpage=1
create table t (s sysname)
insert into t select 'The Quick Brown Fox'
-- convert tabs to spaces
update t set s = replace(s, ' ',' ')
where charindex(' ', s) > 0
-- now do the work.
while 1=1
begin
update t
set s = substring(s, 1, charindex(' ', s, 1)-1) + ' ' + ltrim(substring(s,charindex(' ', s, 1), 8000))
where charindex(' ', s, 1) > 0
if @@rowcount = 0
break
end
select s
from t
答案 9 :(得分:0)
如果要转换的字符串仅包含字母和多个空格[A-Za-z] *,则以下函数将起作用。当这些字符串转换为十六进制时,我发现了一个模式。基于此我的解决方案如下。不是那么优雅,但它不需要任何程序。
unhex(
replace(
replace(
replace(
replace(
replace(
replace(
hex(str)
,204,1014)
,205,1015)
,206,1016)
,207,1017)
,20,'')
,101,20)
)
答案 10 :(得分:0)
遵循我为MySQL 5.6编写的通用函数。我的意图是使用正则表达式来标识空格CR和LF,但是,此版本的mysql不支持它。因此,我必须遍历字符串以查找字符。
CREATE DEFINER=`db_xpto`@`%` FUNCTION `trim_spaces_and_crlf_entire_string`(`StringSuja` text) RETURNS text CHARSET utf8 COLLATE utf8_unicode_ci
DETERMINISTIC
BEGIN
DECLARE StringLimpa TEXT;
DECLARE CaracterAtual, CaracterAnterior TEXT;
DECLARE Contador, TamanhoStringSuja INT;
SET StringLimpa = '';
SET CaracterAtual = '';
SET CaracterAnterior = '';
SET TamanhoStringSuja = LENGTH(StringSuja);
SET Contador = 1;
WHILE Contador <= TamanhoStringSuja DO
SET CaracterAtual = SUBSTRING(StringSuja, Contador, 1);
IF ( CaracterAtual = ' ' AND CaracterAnterior = ' ' ) OR CaracterAtual = '\n' OR CaracterAtual = '\r' THEN
/* DO NOTHING */
SET Contador = Contador;
/* TORNA OS ESPAÇOS DUPLICADOS, CR, LF VISUALIZÁVEIS NO RESULTADO (DEBUG)
IF ( CaracterAtual = ' ' ) THEN SET StringLimpa = CONCAT(StringLimpa, '*');END IF;
IF ( CaracterAtual = '\n' ) THEN SET StringLimpa = CONCAT(StringLimpa, '\\N');END IF;
IF ( CaracterAtual = '\r' ) THEN SET StringLimpa = CONCAT(StringLimpa, '\\R');END IF;
*/
ELSE
/* COPIA CARACTER ATUAL PARA A STRING A FIM DE RECONSTRUÍ-LA SEM OS ESPAÇOS DUPLICADOS */
SET StringLimpa = CONCAT(StringLimpa, CaracterAtual);
/*SET StringLimpa = CONCAT(StringLimpa, Contador, CaracterAtual);*/
SET CaracterAnterior = CaracterAtual;
END IF;
SET Contador = Contador + 1;
END WHILE;
RETURN StringLimpa;
END
答案 11 :(得分:0)
如果您要将具有多个空格的现有列更新为一个,那么此更新查询将很有帮助:
UPDATE
your_table
SETcolumn_that_you_want_to_change
= REGEXP_REPLACE(column_that_you_want_to_change,'[[:space:]] +','');