简体   繁体   English

在MySQL中删除尾随空格

[英]remove trailing whitespace in MySQL

Why does my SELECT not ignore whitespace, and why does TRIM seem to have no effect? 为什么我的SELECT不能忽略空格,为什么TRIM似乎没有作用?

Here are the partial results of something like SELECT DISTINCT crop_year from raw_data : 这是SELECT DISTINCT crop_year from raw_data类的部分结果:

Rows    crop_year
105755  '2010'
12326   '2010 '
256363  '2011'
319321  '2011 '
...

I typed in the single quotes to illustrate the fact that there is trailing whitespace. 我输入单引号来说明存在尾随空格的事实。

I have 2 problems here on my production server... which I cannot replicate locally: 我的生产服务器上有2个问题...我无法在本地复制:

A. I expect SELECT to ignore whitespace, as explained in numerous other questions, as well as the MySQL Docs , but it clearly does not work this way on my prod server. 答:我希望SELECT能够忽略空格,这在许多其他问题以及MySQL Docs中都有说明 ,但是显然它不能在我的产品服务器上以这种方式工作。

B. I expect UPDATE raw_data SET crop_year = TRIM(crop_year) to fix the problem, but running this query results in 0 affected rows. B.我希望UPDATE raw_data SET crop_year = TRIM(crop_year)可以解决此问题,但是运行此查询会导致0个受影响的行。

Other background: This column type is VARCHAR(11). 其他背景:此列类型为VARCHAR(11)。 If it's relevant, the table contains mixed storage engines and collations: this table is MyISAM, and this column is currently latin1_swedish_ci. 如果相关,此表包含混合存储引擎和排序规则:该表是MyISAM,当前此列是latin1_swedish_ci。

PS: In this specific case, year is always a 4 digit value, so I eventually changed the column from a VARCHAR(11) to CHAR(4)... which effectively trimmed the whitespace, but I am still posting the question because I find it likely that I will encounter a similar problem on other columns which are not of a fixed length. PS:在这种特定情况下,year始终是4位数的值,因此我最终将列从VARCHAR(11)更改为CHAR(4)...这有效地修剪了空白,但是我仍在发布问题,因为我发现很可能在长度不固定的其他列上遇到类似的问题。

Figured it out, with help from this question . 这个问题的帮助下,找到了答案。 TRIM does not respect all whitespace... just spaces. TRIM不尊重所有空格...仅尊重空格。 In my case, I needed: 就我而言,我需要:

select distinct trim(BOTH '\\r' from crop_year) as crop_year FROM raw_field_data

Other variations could include 其他变化可能包括

select distinct trim(BOTH '\\n' from crop_year) as crop_year FROM raw_field_data or select distinct trim(BOTH '\\n\\r' from crop_year) as crop_year FROM raw_field_data select distinct trim(BOTH '\\n' from crop_year) as crop_year FROM raw_field_dataselect distinct trim(BOTH '\\n' from crop_year) as crop_year FROM raw_field_data select distinct trim(BOTH '\\n\\r' from crop_year) as crop_year FROM raw_field_data select distinct trim(BOTH '\\n' from crop_year) as crop_year FROM raw_field_data select distinct trim(BOTH '\\n\\r' from crop_year) as crop_year FROM raw_field_data

Maybe you place extra space in your "form" when you enter the value on the crop year. 当您输入作物年度的值时,也许在“表单”中放置了额外的空间。 check your input forms maybe... 检查您的输入表格,也许...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM