简体   繁体   English

如何在不丢失数据的情况下改变MySQL表?

[英]How to alter MySQL table without losing data?

In my application, I make some changes and upload them to a testing server. 在我的应用程序中,我进行了一些更改并将它们上传到测试服务器。 Because I have no access to the server database I run ALTER commands to make changes on it. 因为我无法访问服务器数据库,所以我运行ALTER命令对其进行更改。

Using a method I ran the following command on server: 使用方法我在服务器上运行以下命令:

ALTER TABLE `blahblahtable` ADD COLUMN `newcolumn` INT(12) NOT NULL

After that, I found that the all the data of the table has been removed. 之后,我发现表的所有数据都已删除。 Now the table is blank. 现在表格是空白的。

So I need to alter the table without removing his data. 所以我需要改变表而不删除他的数据。 Is there any way to do that? 有没有办法做到这一点?

Your question is quite obvious. 你的问题非常明显。 You're adding a new column to the table, and setting it to NOT NULL . 您正在向表中添加新列,并将其设置为NOT NULL
To make things clearer, I will explain the reaction of the server when you run the command: 为了使事情更清楚,我将在运行命令时解释服务器的反应:

  1. You add a new column, so every row of the table has to set a value for that column. 您添加了一个新列,因此表的每一行都必须为该列设置一个值。

  2. As you don't declare any default value , all the rows set null for this new column. 由于您未声明任何默认值 ,因此所有行都为此新列设置了null

  3. The server notices that the rows of the table have a null value on a column that doesn't allow null s. 服务器注意到表的行在不允许null的列上具有null值。 This is illegal. 这是非法的。

  4. To solve the conflict, the invalid rows are deleted . 要解决冲突,将删除无效行。

There are some good fixes for this issue: 这个问题有一些很好的解决方法:

  • Set a default value (recommended) for the column you're creating. 为您正在创建的列设置默认值 (推荐)。

  • Create the column without the NOT NULL , set the appropiate values, and then make the column NOT NULL . 创建没有 NOT NULL的列,设置适当的值,然后使列NOT NULL

您可以创建临时表,传递要更改的表中的所有信息,然后将信息返回到更改的表。

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

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