mysql: how to truncate the length of a field

房东的猫 提交于 2019-11-28 07:21:26

问题


Alter table merry_parents change mobile mobile char(10).

When I do the above I'm getting error:

#1265 - Data truncated for column 'mobile' at row 2

How can I truncate my mobile field to char(10)? Currently it is char(12).


回答1:


The error is telling you that there is data 12 characters long in row 2 (and probably others) so it's stopped the alter command to avoid losing data.

Try updating your table using SUBSTRING() to shorten the column. It's unclear why you want to do this as you'll lose data, but this will truncate the data to 10 characters long:

UPDATE merry_parents SET mobile=SUBSTRING(mobile, 1, 10)

Then run your alter command:

ALTER TABLE merry_parents CHANGE mobile mobile char(10).



回答2:


If you are ok with truncating the data at 10 characters - you can update the column first, then resize it

UPDATE <tablename> set mobile = left(mobile, 10);

Then run your alter statement.




回答3:


If you are willing to just have the data truncated, you can do it in one step by using the IGNORE option on the ALTER:

ALTER IGNORE TABLE merry_parents MODIFY mobile char(10);



回答4:


You have data that has more characters than the length of the column that you are trying to alter it into.

Or you have a null value in the specified field.

http://bugs.mysql.com/bug.php?id=14742



来源:https://stackoverflow.com/questions/9611100/mysql-how-to-truncate-the-length-of-a-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!