不能 trim() Char(195) 在 MySQL

Can't trim() Char(195) in MySQL

我导入并正在清理从旧大型机导出的一些数据,并且有很多行以异常字符(即 ASCII 字符 194、195、226 等)开头。我可以用一个简单的 remainder = trim(leading '%' from remainder) trim 关闭大部分字符(其中 '%' 代表有问题的字符。

唯一不会删除的字符是“Í”。如果我 运行 一个 remainder = trim(leading 'Í' from remainder) 查询它不会找到并且 trim 字符,如果我 运行 一个 ascii(remainder) 查询我的数据它显示为以该字符开头的字符串的第 195 个字符。

接下来我 运行 一个 remainder = trim(leading CHAR(195) from remainder) 查询并且也跳过了字符。

为什么我能够删除除了这个字符以外的所有其他字符,而显然 MySQL 可以将其转换为 ASCII 字符代码,并且在正常显示字符时没有任何问题 select查询是 运行 并显示适用的记录?

更新 我还有 运行 以下查询:

remainder = trim(leading convert('Í' using ASCII) from remainder)

remainder = trim(leading convert('Í' using UTF8) from remainder)

remainder = trim(leading convert(Char(195) using ASCII) from remainder)

所以我终于找到了一个方法。使用

remainder = trim(leading Char(195) from convert(remainder using ASCII))

我终于摆脱了那个讨厌的“Í”。我唯一担心的是它真的没有 trim ,它把通常属于 'Extended ASCII' 代码列表的超过 127 的 ASCII 字符 ALL 变成了“?”然后可以使用 remainder = trim(leading '?' from remainder) 将其删除。它适用于我当前的任务,但我对更精确的查询感兴趣,这些查询可以在将来需要时删除特定字符。

你的 table 使用什么 CHARSET

如果您确定 table 中有 ASCII 数据并且字符代码正确,则 TRIM 函数没有问题。

所以在查询之前,只需弄清楚您的数据table 甚至列 CHARSET。

http://sqlfiddle.com/#!9/1cfe9/5

SELECT TRIM(LEADING CHAR(195) FROM field1)
, field1
from t1

您的查询在我的 MySQL ( 5.5.44-0ubuntu0.14.04.1 ) 上正常工作。

它对您不起作用的原因可能是,由于字符集不匹配,您视为字符 195 不是字符总共 195;例如,它可能是一个 0xCD 十六进制,或者一个对应于 0xC38D 十六进制的 UTF8 序列,在这种情况下,trim输入“Í”显然会把它转换成更奇怪的东西。

尝试使用 HEX() 来检查有问题的字符。这是什么?

CD     Latin1 Í
C38D   UTF8   Í      <---
C3     CHAR(195)

请注意,Í 根本不是 CHAR(195),但 195 开头 在 UTF8 中的一个 Í。

在紧要关头,您可以以十六进制执行操作...

select unhex(trim(leading 'C38D' from HEX('Íturalde')));
+---------------------------------------------------+
| unhex(trim(leading 'C38D' from HEX('Íturalde')))  |
+---------------------------------------------------+
| turalde                                           |
+---------------------------------------------------+

这将 曾经 trim 领先的 C38D 或 UTF8 Í,而忽略其他所有内容。

更新:您可能想将 table 转储到文本文件并尝试 运行 recodeiconvfixcode 就可以了。