如何修改MySQL列以允许NULL而不指定其数据类型?

时间:2022-05-19 07:18:35

I have a table in mysql and I want to alter a table to allow a column to be null.

我在mysql中有一个表,我想要修改一个表,使列为空。

When I do describe on my mysql table, I see these things in mysql workbench:

当我在mysql表上描述时,我在mysql workbench中看到这些东西:

Field       Type        Null        Key     Default     Extra

I want to set Null field as YES for a particular column. Here is how I am trying which works fine but do I need to provide its data type while setting DEFAULT to NULL?

我想为特定的列设置零字段。这里是我尝试的方法,它工作得很好,但是我是否需要在将默认值设置为NULL时提供它的数据类型?

ALTER TABLE abc.xyz CHANGE hello hello int(10) unsigned DEFAULT NULL;
ALTER TABLE abc.xyz CHANGE world world int(10) unsigned DEFAULT NULL;

Is there any other way by which I can just pick column name and set default to NULL instead of using its data type as well? I don't want to provide int(10) while setting its default to NULL.

有没有其他方法可以让我选择列名并将默认值设置为NULL而不是使用它的数据类型?我不想在将默认值设置为NULL时提供int(10)。

2 个解决方案

#1


5  

You're kind of on the wrong track. Changing the default to NULL does not "allow" the column to be null: what you need to do is drop the "NOT NULL" constraint on the column.

你有点走错路了。将默认值更改为NULL不会“允许”列为NULL:您需要做的是删除列上的“not NULL”约束。

But to redefine the nullability of a column through script, you will have to continue to reference the datatype. You'll have to enter something like

但是要通过脚本重新定义列的可空性,您必须继续引用数据类型。你必须输入类似的东西

 ALTER TABLE MyTable MODIFY COLUMN this_column Int NULL;

#2


2  

Not sure if this applies if you're looking for a straight DDL statement, but in MySQL Workbench you can right-click on a table name, select "Alter Table..." and it will pull up a table definition GUI. From there, you can select null/not null (among all the other options) without explicitly listing the column's datatype. Just a "for what it's worth"...

如果您正在寻找一个直接的DDL语句,但是在MySQL Workbench中,您可以右键单击一个表名,选择“Alter table…”,并且它将拉起一个表定义GUI。从这里,您可以选择null/not null(在所有其他选项中),而不必显式列出列的数据类型。只是“为了它的价值”……

#1


5  

You're kind of on the wrong track. Changing the default to NULL does not "allow" the column to be null: what you need to do is drop the "NOT NULL" constraint on the column.

你有点走错路了。将默认值更改为NULL不会“允许”列为NULL:您需要做的是删除列上的“not NULL”约束。

But to redefine the nullability of a column through script, you will have to continue to reference the datatype. You'll have to enter something like

但是要通过脚本重新定义列的可空性,您必须继续引用数据类型。你必须输入类似的东西

 ALTER TABLE MyTable MODIFY COLUMN this_column Int NULL;

#2


2  

Not sure if this applies if you're looking for a straight DDL statement, but in MySQL Workbench you can right-click on a table name, select "Alter Table..." and it will pull up a table definition GUI. From there, you can select null/not null (among all the other options) without explicitly listing the column's datatype. Just a "for what it's worth"...

如果您正在寻找一个直接的DDL语句,但是在MySQL Workbench中,您可以右键单击一个表名,选择“Alter table…”,并且它将拉起一个表定义GUI。从这里,您可以选择null/not null(在所有其他选项中),而不必显式列出列的数据类型。只是“为了它的价值”……