分享

6、约束管理、索引管理、键管理

 思懿 2021-06-05
非空约束
#设置非空约束
> alter table testtb modify name varchar(100) not null;
#删除非空约束
> alter table testtb modify name varchar(100) null;
自动增长
#添加
> alter table testtb modify id int auto_increment;
> alter table testtb change id id int auto_increment;
#自动增长
> alter table testtb change id id int;
> alter table testtb modify id int;
主键约束
# 添加主键约束
> alter table testtb4 add primary key(id);
> alter table testtb4 add constraint primary key(id);
# 删除主键约束
> alter table testtb drop primary key;
唯一键约束
#添加
> alter table testtb add unique key(uid);
> alter table testtb add unique key uni_test(test);
#删除
> alter table testtb drop index uni_test;
查看约束
#查看主键/唯一键/外键
> select * from information_schema.key_column_usage where table_name='test1';
#只查看主键
> desc test1
#查看test1表中引用了那些表中的主键作为自己的外键
> select TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME,REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME from information_schema.KEY_COLUMN_USAGE where TABLE_NAME = 'test1' and REFERENCED_TABLE_NAME is not null;
#查看test2表的主键被哪些表引用成为外键
> select REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME,CONSTRAINT_NAME,TABLE_NAME,COLUMN_NAME from information_schema.KEY_COLUMN_USAGE where REFERENCED_TABLE_NAME = 'test2';
外键约束
# 添加
> alter table testtb add column tid int default 0 not null;
> alter table testtb add constraint testtb_tid_fk foreign key(tid) references testtb2(id);
# 删除
> alter table test4 drop foreign key test_tid_fk;
索引管理
#添加
> alter table testtb add index ind_name(name);

create index ind_name on testtb (name(20) desc);
create index ind_name on testtb (name(20));
create index ind_name on testtb (name);

# 联合索引
> create index ind_id_name on testtb1 (id,name);
> create index ind_id_name on testtb1 (id,name(20));

#重建索引
> repair table table_name quick;

#删除索引
> alter table test2 drop index uu_ttt;

#查看索引
> show index from testtb;
> show index from testtb where key_name like 'ind%';

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多