-
use test;
-
show tables;
-
-
/*建立一张省份表作为测试*/
-
create table province(pid tinyint unsigned primary key auto_increment,pname varchar(20) unique key not null default "jiangxi");
-
-
show index from province;
-
show create table province;
-
desc province;
-
-
insert into province(pname) values("shanghai");
-
insert into province(pname) values("beijing");
-
insert into province(pname) values("fujian");
-
-
delete from province where pid=2;
-
-
select * from province;
-
-
drop table province;
-
-
-
/*******************************修改数据表*****************************************************/
-
-
/*增加单列语法 alter table table_name add [column] col_name column_definition [first|after col_name];*/
-
alter table province add code varchar(10) not null after pname;
-
-
/*增加多列语法 alter table table_name add [column] (col_name column_definition,...);注意没有位置选项*/
-
alter table province add (code varchar(10) not null,population_sum bigint not null);
-
-
/*删除列语法 alter table table_name drop [column] column_name*/
-
alter table province drop code;
-
-
/*添加约束 alter table table_name add [constraint[symbol]] primary key [index_type] (index_col_name,...);其它约束也是一样的*/
-
create table province(pid tinyint unsigned,pname varchar(20));
-
alter table province add constraint pk primary key (pid);/*pk是约束的名字,一般不用*/
-
alter table province add foreign key (pid) references XXX (XXX);/*添加外键约束也是一样的*/
-
-
/*删除约束就是drop*/
-
-
/*修改列定义语法:alter table table_name modifies [column] column_name column_definition [first|after col_name]*/
-
-
/*修改列名称语法: alter table table_name change [column] old_col_name new_col_name column_definition [first|after col_name]*/
-
-
/*修改表名称语法: 1.alter table table_name rename [to|as] new _table_name;
-
2.rename table table_name to new_table_name [,table_name2 to new_table_name2...];*/
-
-
/********************************************************************************************/
-
-
-
-
/*******************************外键**********************************************************/
-
/*注意,1.建立外键时,子表和父表必须为innoDB引擎,这是默认的引擎。可以在my.cnf中配置
-
2.如果外键列的字段名为数值型,则必须与参考列的字段类型和有无符号一致
-
3.如果外键列的字段名为字符类型,则字符的长度可以不一致。
-
*/
-
-
/*外键约束的参照操作*/
-
-
/*1.cascade :cascade翻译过来时串联的意思。父表中删除或者更新时,对应的自动删除或者更新子表中匹配的行*/
-
create table users(id smallint primary key auto_increment,username varchar(20) not null,pid tinyint unsigned,foreign key (pid) references province(pid) on delete cascade);
-
insert into users(username,pid) values("xiebiao",1);
-
insert into users(username,pid) values("vibexie",2);
-
insert into users(username,pid) values("kobe",3);
-
select * from users;
-
desc users;
-
show create table users;
-
-
show index from users;
-
drop table users;
-
-
/*2.set null:父表中删除或者更新,并设置子表中的外键列为NULL.如果使用set null,必须保证子表列没有指定not null*/
-
-
/*3.restrict: 拒绝父表的删除或者更新操作*/
-
-
/*4.no action:标准的sql关键字,在mysql中与restrict一致*/
- /**************************************************************************************/