简体   繁体   English

将新的 NOT NULL 列添加到包含数据的现有表

[英]Adding a new NOT NULL column to an existing Table with data

I want to add a new NOT NULL column to an existing table which has data in MySQL 5.7.我想在现有表中添加一个新的NOT NULL列,该表在 MySQL 5.7 中有数据。 I have seen this question and I am using the solution suggested there.我已经看到了这个问题,我正在使用那里建议的解决方案。

I am adding the new column as NULL , populate data for the new column and then change the column from NOT NULL to NULL .我将新列添加为NULL ,填充新列的数据,然后将列从NOT NULL更改为NULL

-- 1. add new column as null
ALTER TABLE `mytable` ADD COLUMN newCol BIT NULL AFTER curCol;

-- 2. populate default data for new column
SET sql_safe_updates = 0;
UPDATE `mytable` SET newCol = 0;
SET sql_safe_updates = 1;

-- 3. change the column to NOT NULL
ALTER TABLE `mytable` ALTER COLUMN newCol BIT NOT NULL;

But I am getting the following error on the last command:但是我在最后一个命令中收到以下错误:

Error Code: 1064. You have an error in your SQL syntax;错误代码:1064。您的 SQL 语法有错误; check the manual that corresponds to your MySQL server version for the right syntax to use near 'BIT NOT NULL:' at line 1检查与您的 MySQL 服务器版本相对应的手册,以获取在第 1 行的“BIT NOT NULL:”附近使用的正确语法

This piece of SQL is not valid in MySQL:这条 SQL 在 MySQL 中无效:

ALTER TABLE `mytable` ALTER COLUMN newCol BIT NOT NULL;

Instead, consider:相反,请考虑:

ALTER TABLE `mytable` MODIFY newCol BIT NOT NULL;

Reference: MySQL ALTER TABLE syntax参考: MySQL ALTER TABLE语法

You can do this in three steps:您可以分三个步骤执行此操作:

  1. Add your new column (initially, let it have NULL values)添加您的新列(最初,让它具有NULL值)

     ALTER TABLE my_table ADD COLUMN new_col datatype NULL AFTER cur_col;
  2. Update the table so that there are no NULL in our new column更新表格,使我们的新列中没有NULL

     UPDATE my_table SET new_col = 0 WHERE new_col IS NULL;
  3. Modify our new column to NOT NULL将我们的新列修改为NOT NULL

     ALTER TABLE my_table MODIFY COLUMN new_col datatype NOT NULL;

Reference: StackOverflow- Altering a column: null to not null参考: StackOverflow-更改列:null 改为非 null

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

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