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