[英]MySQL Alter table add column with default of 1
I have read most of the posts concerning MySQL ALTER TABLE but can't find an answer to my issue. 我已经阅读了有关MySQL ALTER TABLE的大多数文章,但是找不到我的问题的答案。
I have a script that adds a new column to a table, this works fine but the issue I have is it is not setting the default value for the new column. 我有一个向表中添加新列的脚本,它可以正常工作,但是我遇到的问题是它没有为新列设置默认值。 Am I missing something:
我错过了什么吗?
ALTER TABLE Hist ADD S1 VARCHAR( 5 ) DEFAULT '1', ADD comments_S1 TEXT
The above is the code I am using. 上面是我正在使用的代码。
Any idea's 有任何想法吗
Many thanks in advance for your time. 非常感谢您的宝贵时间。
Alas, the default
value gets used only for new rows. ,,
default
值仅用于新行。 The old rows get NULL
. 旧行为
NULL
。 So, simply update them after the alter table: 因此,只需在alter table之后更新它们:
update hist
set s1 = '1';
This is not really well documented in MySQL, but it is sort-of suggested . 这在MySQL中并没有得到很好的记录 ,但建议使用。 .
。
Alterations that modify only table metadata and not table data are immediate because the server only needs to alter the table .frm file, not touch table contents.
仅修改表元数据而不修改表数据的更改是立即进行的,因为服务器仅需要更改表.frm文件,而无需更改表内容。 The following changes are fast alterations that can be made this way:
以下更改是可以通过这种方式进行的快速更改:
.
。 .
。 .
。 - Changing the default value of a column (except for NDB tables).
-更改列的默认值(NDB表除外)。
Adding a column does require a table copy. 添加列确实需要表副本。 But the old values are not affected.
但是旧的值不受影响。
I believe the syntax for adding a column to a MySQL table is: 我相信将列添加到MySQL表的语法是:
ALTER TABLE table_name ADD COLUMN col type DEFAULT 'default';
You are missing the keyword COLUMN
from your syntax. 您的语法中缺少关键字
COLUMN
。 Try the following: 请尝试以下操作:
ALTER TABLE Hist
ADD S1 VARCHAR(5) DEFAULT '1',
ADD comments_S1 TEXT;
Seems like something in Your application code sets S1 field to empty string. 似乎您的应用程序代码中的某些内容将S1字段设置为空字符串。
ALTER TABLE Hist
ADD S1 VARCHAR(5) DEFAULT '1' NOT NULL,
ADD comments_S1 TEXT;
it will prevent S1 from being empty and automatically change NULL
fields to '1'
它将防止S1为空,并自动将
NULL
字段更改为'1'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.