MySQL 如何删除非空约束?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2607775/
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 15:44:57  来源:igfitidea点击:

How can a not null constraint be dropped?

mysqlnullconstraints

提问by Tomislav Nakic-Alfirevic

Let's say there's a table created as follows:

假设创建了一个表,如下所示:

create table testTable ( colA int not null )

How would you drop the not null constraint? I'm looking for something along the lines of

您将如何删除非空约束?我正在寻找类似的东西

ALTER TABLE testTable ALTER COLUMN colA DROP NOT NULL;

which is what it would look like if I used PostgreSQL. To my amazement, as far as I've been able to find, the MySQL docs, Google and yes, even Stackoverflow (in spite of dozens or hundreds of NULL-related questions) don't seem to lead towards a single simple SQL statement which will do the job.

如果我使用 PostgreSQL,这就是它的样子。令我惊讶的是,据我所知,MySQL 文档、Google 和是的,甚至 Stackoverflow(尽管有数十或数百个与 NULL 相关的问题)似乎都没有导致一个简单的 SQL 语句这将完成这项工作。

回答by michael.zischka

I would try something like this

我会尝试这样的事情

ALTER TABLE testTable MODIFY COLUMN colA int;

回答by Seva Alekseyev

In MySQL, nullability is a part of the datatype, not a constraint. So:

在 MySQL 中,可空性是数据类型的一部分,而不是约束。所以:

ALTER TABLE testTable MODIFY COLUMN colA int null; 

回答by Noah Ternullo

The syntax was close its actually:

语法实际上是接近的:

ALTER TABLE testTable CHANGE colA colA int null;

回答by Pratik Kar

Try

尝试

ALTER TABLE testTable MODIFY COLUMN columnA int;

回答by B-shan

This works for me

这对我有用

ALTER TABLE table_name
MODIFY COLUMN column_name VARCHAR(25) UNIQUE;

回答by Tushar Zagade

When you modify table constraint or datatype in Mysql workbench then it shows the code it is going to execute to complete the request. And this is the query I got from that box.

当您在 Mysql 工作台中修改表约束或数据类型时,它会显示将要执行以完成请求的代码。这是我从那个盒子里得到的查询。

ALTER TABLE `table_name`.`column_name`  CHANGE COLUMN `column_name` `colunm_name`datatype NULL ;

But the catch here is that you can't have the primary key as null you have to set it unique instead.

但这里的问题是,您不能将主键设为 null,而必须将其设置为唯一键。

回答by Chaitanya

ALTER TABLE test.tbl_employee 
CHANGE COLUMN `DepartmentId` `DepartmentId` INT(11) NULL;