如何从 MySQL 的列中删除“NOT NULL”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3000901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 16:14:48  来源:igfitidea点击:

How do I drop 'NOT NULL' from a column in MySQL?

mysqlalter-table

提问by Will

A show create table command shows the following:

show create table 命令显示以下内容:

'columnA' varchar(6) NOT NULL DEFAULT '';

How do I modify that column so that the not null is removed? I need it to be:

如何修改该列以删除非空值?我需要它是:

'columnA' varchar(6) DEFAULT NULL;

I thought the following would work, but it has no effect:

我认为以下方法可行,但没有效果:

ALTER TABLE tbl_name MODIFY columnA varchar(6) DEFAULT NULL;

回答by Eric Petroelje

Try this instead:

试试这个:

ALTER TABLE tbl_name MODIFY columnA varchar(6) NULL DEFAULT NULL; 

回答by Rob Van Dam

Normally, Eric's answer should work:

通常,埃里克的回答应该有效:

ALTER TABLE tbl_name MODIFY columnA varchar(6) NULL DEFAULT NULL; 

(Although the 'NULL DEFAULT NULL' part is optional).

(尽管 'NULL DEFAULT NULL' 部分是可选的)。

But like you, I had a case that just returned OK without doing anything. In my case it appears to be due to the fact that my key was part of the primary key. So I had to do the following:

但是和你一样,我有一个案例,没有做任何事情就返回正常。就我而言,这似乎是由于我的密钥是主键的一部分。所以我不得不做以下事情:

ALTER TABLE tbl_name DROP PRIMARY KEY;
ALTER TABLE tbl_name MODIFY columnA varchar(6);
ALTER TABLE tbl_name ADD PRIMARY KEY (columnA);

with that last query specifying whatever your primary key actually is.

最后一个查询指定您的主键实际上是什么。

Also, in case anyone thinks that is too verbose, the following combined query does NOT work, even though it should be identical:

此外,如果有人认为这太冗长,以下组合查询不起作用,即使它应该是相同的:

ALTER TABLE tbl_name DROP PRIMARY KEY, MODIFY columnA varchar(6), ADD PRIMARY KEY (columnA);

I assume that mysql rewrites that last query into a different order so that the primary key still exists when the modify is performed, hence the need to break it out into three statements.

我假设 mysql 将最后一个查询重写为不同的顺序,以便在执行修改时主键仍然存在,因此需要将其分解为三个语句。

FYI, this is on mysql 5.1.47 but I haven't yet found any documentation indicating why this happens so I don't know what versions are affected.

仅供参考,这是在 mysql 5.1.47 上,但我还没有找到任何说明为什么会发生这种情况的文档,所以我不知道哪些版本会受到影响。

回答by Bob Fanger

Make the change (locally) in phpMyAdmin. It will show the query it used for the change. Execute this query in production and you're done.

在 phpMyAdmin 中进行更改(本地)。它将显示用于更改的查询。在生产中执行此查询,您就完成了。

You can use this strategy in any GUI tool to see the queries it performs. I personally use Sequel Pro (for Mac OS X)instead of phpMyAdmin.

您可以在任何 GUI 工具中使用此策略来查看它执行的查询。我个人使用Sequel Pro(适用于 Mac OS X)而不是 phpMyAdmin。