简体   繁体   English

MySQL将错误的数据类型导入VARCHAR列

[英]MySQL imported wrong datatype into a VARCHAR column

Today I did something stupid: I had a list of card numbers in an excel file that I had to import to a DB table somehow. 今天我做了一些愚蠢的事情:我有一个excel文件中的卡号列表,我不得不以某种方式导入到数据库表中。 So i exported the numbers to CSV file, but without any quotes (don't ask me why). 所以我将数字导出到CSV文件,但没有任何引号 (不要问我为什么)。 The file looked like: 该文件看起来像:

123456
234567
345678
...

Then I created a table with a single VARCHAR(22) column and did a 然后我创建了一个包含单个VARCHAR(22)列的表并执行了一个

LOAD DATA LOCAL INFILE 'numbers.csv' INTO TABLE cards

This worked fine, apart from many warnings, which I ignored (the other stupid thing I did). 这很好,除了许多警告,我忽略了(我做的另一个愚蠢的事情)。 After that I tried to query with this SQL: 之后我试着用这个SQL查询:

SELECT * FROM cards WHERE number='123456'

which gave me an empty result. 这给了我一个空洞的结果。 Whereas this works: 虽然这有效:

SELECT * FROM cards WHERE number=123456

Notice the missing quotes! 注意缺少的引号! So it seems, that I managed to populate my VARCHAR table with INTEGER data. 所以看来,我设法用INTEGER数据填充我的VARCHAR表。 I have no idea how that is possible at all. 我根本不知道这是怎么回事。

I already tried to fix this with an UPDATE like this 我已经尝试用这样的UPDATE解决这个问题

UPDATE cards SET number = CAST(number AS CHAR(22))

But that didn't work. 但那没用。

So is there a way to fix this and how could this even happen? 那么有没有办法解决这个问题,这怎么可能发生呢?

This is the result of some implicit conversion in order to do a numerical comparison: 这是一些隐式转换的结果,以便进行数值比较:

SELECT * FROM cards WHERE number='123'

This will only match against text fields that are literally "123" and will miss on " 123" and "123\\r" if you have those. 这只会匹配字面上为"123"文本字段,如果你有这些字段将会错过" 123""123\\r" For some reason, "123 " and "123" are considered "equivalent" presumably do to trailing space removal on both sides. 出于某种原因, "123 ""123"被认为是“等同的”,可能是两侧的尾随空间去除。

When doing your import, don't forget LINES TERMINATED BY '\\r\\n' . 在进行导入时,不要忘记LINES TERMINATED BY '\\r\\n' If you're ever confused about what's in a field, including hidden characters, try: 如果您对某个字段中包含隐藏字符的内容感到困惑,请尝试:

SELECT HEX(number) FROM cards

This will show the hex-dumped output of each string. 这将显示每个字符串的十六进制转储输出。 Things like 20 indicate space, just as %20 in a URL is a space. 20这样的东西表示空间,就像URL中的%20是空格一样。

You can also fix this by: 您还可以通过以下方式解决此问

UPDATE cards SET number=REPLACE(number, '\r', '')

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

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