如何向 MySQL 中的现有列添加非空约束
我有一个名为“Person”的表名称,其列名称如下,
P_Id(int),
LastName(varchar),
FirstName (varchar).
我忘记给 P_Id
提供 NOT NULL
约束。
现在我尝试使用以下查询将 NOT NULL
约束添加到名为 P_Id
的现有列,
1. ALTER TABLE Person MODIFY (P_Id NOT NULL);
2. ALTER TABLE Person ADD CONSTRAINT NOT NULL NOT NULL (P_Id);
我收到语法错误......
I have table name called "Person" with following column names
P_Id(int),
LastName(varchar),
FirstName (varchar).
I forgot to give NOT NULL
Constraint to P_Id
.
Now I tried with following query to add NOT NULL
Constraint to existing column called P_Id
,
1. ALTER TABLE Person MODIFY (P_Id NOT NULL);
2. ALTER TABLE Person ADD CONSTRAINT NOT NULL NOT NULL (P_Id);
I am getting syntax error....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需使用
ALTER TABLE... MODIFY...
查询并将NOT NULL
添加到现有的列定义中。例如:请注意:使用
MODIFY
查询时,您需要再次指定完整列定义。例如,如果您的列具有DEFAULT
值或列注释,则需要在MODIFY
语句中指定它以及数据类型和NOT NULL
,否则会丢失。防止此类事故的最安全做法是从SHOW CREATE TABLE YourTable
查询的输出中复制列定义,修改它以包含NOT NULL
约束,然后粘贴将其放入您的ALTER TABLE...MODIFY...
查询中。Just use an
ALTER TABLE... MODIFY...
query and addNOT NULL
into your existing column definition. For example:A word of caution: you need to specify the full column definition again when using a
MODIFY
query. If your column has, for example, aDEFAULT
value, or a column comment, you need to specify it in theMODIFY
statement along with the data type and theNOT NULL
, or it will be lost. The safest practice to guard against such mishaps is to copy the column definition from the output of aSHOW CREATE TABLE YourTable
query, modify it to include theNOT NULL
constraint, and paste it into yourALTER TABLE... MODIFY...
query.尝试一下,您就会知道更改和修改之间的区别,
CHANGE
更改特定列的名称和数据类型。MODIFY
修改特定列的数据类型。您不能使用此语句更改列的名称。希望,我解释得很详细。
Try this, you will know the difference between change and modify,
CHANGE
.MODIFY
. You cannot change the name of the column using this statement.Hope, I explained well in detail.
想要添加:
更新后,例如
如果您得到
确保首先更新表以在相关列中包含值(因此它不为空)
Would like to add:
After update, such as
If you get
Make sure you update the table first to have values in the related column (so it's not null)