mysql 数据库创建 自己 心得

在找工作的我 努力实现自己的梦想

在创建自己的数据库事 发现自己连 主键 和 外键 ,   索引 都创建不了。。花了一天的时间去寻找我想要的答案ing....

原来 自己 在创建数据库的同时 忘记数据的一致性 ,

cretae table a

(id int primary ke not null,

name varchar(40) nto null

)type=innodb;

 

create table b

(bid int primary key not null,

aid varchar(40) not null,

btext  varchar(40) not null

)type=innodb;

红色部分要注意。

蓝色部分必须的。

还有就是 创建主键见 直接 写表里  bid int primary key not null

或者外部创建也行 alter table  (table_name) add constraint  pk_bid primary key (bid); 

创建索引 表内创建: index [indexName] (  aid  )

create table b

(bid int primary key not null,

aid varchar(40) not null,

btext  varchar(40) not null,

index [indexName] (  aid  )

)type=innodb;

表外创建:

alter tabel table_name add index indx_name (column_list)

样板:

alter tabel  b  add index indx_name    aid  ; 

现在创建好索引了 可以创建外键了 因为 创建外键必须副表 要创建的那个值要先创建索引 

同样表内创建:  constraint fk_name foreign key  (aid) references a(id) on update cascade on delete set null 

create table b

(bid int primary key not null,

aid varchar(40) not null,

btext  varchar(40) not null,

index [indexName] (  aid  ),

constraint fk_name foreign key  (aid) references a(id) on update cascade on delete set null

)type=innodb;

外部创建:

alter table  (table_name)  add constraint fk_name foreign key (column_name_from) references other_table_name(column_name_to) on update cascade on delete set null;

样板:

alter table  b add constraint fk_name foreign key  aid  references  a(id)  on update cascade on delete set null;

 

 

 

 

 

posted on 2013-03-08 22:53  别停下来  阅读(574)  评论(0编辑  收藏  举报