mysql中一些简单的对表结构进行的操作

首先定义一个最简单的表:

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'
才可以。

posted on 2009-10-30 18:56 duduli 阅读(652) 评论(0)  编辑  收藏 所属分类: 数据库


只有注册用户登录后才能发表评论。


网站导航:
 
<2009年10月>
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567

导航

统计

公告

welcome to my place.

常用链接

留言簿(5)

我参与的团队

随笔分类

随笔档案

新闻分类

石头JAVA摆地摊儿

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜

@duduli