首先定義一個(gè)最簡(jiǎn)單的表:
create table user_test (
id int,
name varchar(20),
descrb text
);
這是一個(gè)再簡(jiǎn)單不過(guò)的表了。現(xiàn)在我要對(duì)這個(gè)表的結(jié)構(gòu)進(jìn)行操作。
首先,對(duì)id設(shè)置不能為空,
alter table user_test modify id int not null;
這個(gè)id我想讓系統(tǒng)自動(dòng)生成,又要使用alter 命令了。
alter table user_test change id id not null auto_increment;
這樣行了吧。但是mysql給報(bào)了一個(gè)錯(cuò),
ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key
說(shuō)如果是自動(dòng)增加的話(huà)必須是是一個(gè)主鍵。
所以上面的那個(gè)語(yǔ)句必須修改為。
我想將descrb的列名修改成為descb。
alter table user_test change descrb descb text;
對(duì)了學(xué)生不是有班級(jí)嗎?我想加入一個(gè)班級(jí)的列名,類(lèi)型為varchar(10)的。
alter table user_test add class varchar(10);
現(xiàn)在我想對(duì)descb字段進(jìn)行一個(gè)賦default值。
使用的命令為:
alter table user_test alter table descb set default "student";
卻報(bào)了一個(gè)錯(cuò)誤,意思是clob或是text類(lèi)型不能有初始值。
只能修改他的類(lèi)型。
還記得之前的命令嗎?
alter table user_test change descb descb varchar(100);
然后再使用賦初始值的命令。
表是建立成功了,但是別人使用的時(shí)候卻說(shuō)表的名字不是很好,又要我改表明。
改成stdmsg,使用的命令是
alter table user_test rename to stdmsg;
表名也改好啦,問(wèn)題又出來(lái)啦,同一個(gè)班級(jí)中不能有名字相同的人,這有要建立一個(gè)聯(lián)合主鍵了。
alter table stdmsg add constraint UN_nc unique (class,name);
或是:
alter table stdmsg add constraint primary key PK_cn(class,name);
unique和primary key之間的區(qū)別,我所知道很少,第一unique可以為空,而且一個(gè)表上可以建立多個(gè)。而設(shè)置primary key的話(huà),字段不能為空。
mysql數(shù)據(jù)庫(kù)會(huì)將其自動(dòng)設(shè)置為不為空。
如果想drop掉主鍵的話(huà),
對(duì)應(yīng)的drop方法是不同的。
alter table test drop index UN_nc;
--針對(duì)于unique的drop。
alter table test drop primary key;
--針對(duì)于primary key的。
新的需求又來(lái)了,我的這個(gè)stdmsg表中要添加一個(gè)學(xué)生,出生日期的列。
alter table stdmsg add birth data;
我要對(duì)這個(gè)birth進(jìn)行一個(gè)check讓它在在‘1980-01-01’到‘1990-01-01’之間
添加一個(gè)check
alter table stdmsg add constraint U_check check(birth>'1985-01-01' and birth<'1990-01-01');
測(cè)試這個(gè)check有用沒(méi)有,
insert into stdmsg(name,class,birth) values ('tom','great_3','2001-12-30');
但是這個(gè)insert 卻還是插入進(jìn)去了,上Google找了下,基本知道m(xù)ysql的check是沒(méi)有用的。
mysql中的auto_commit。一般默認(rèn)為自動(dòng)提交的,也就是autocommit=0;
測(cè)試了一下使用autocommit=1;但是好像不是成功的。
如果想啟動(dòng)mysql不想自動(dòng)提交的話(huà),要設(shè)置mysql的my.ini文件中的配置。
init_commit ='set autocommit=1'
才可以。