【MySql】外键,自增

1,在创建表的同时添加外键

 1 create table users(
 2    userID       int             primary key auto_increment,
 3    username     varchar(20)     not null,
 4    password     varchar(20)     not null
 5    )auto_increment = 1001;
 6    
 7 
 8 create  table userRight(
 9    ID         int            primary key  auto_increment,
10    userID     int            not null,
11    constraint FK_constr  foreign key(userID)  references users(userID)
12    on delete cascade 
13    on update cascade);
  指定主键关键字:foreign key (列名)

       引用外键关键字:references <外键表名>(外键列名)

       事件触发限制:on delete 和 on update ,可设参数cascade(跟随外键改动),restrict(限制外键中的外键改动),set NULL(设空值),set Default(设默认值)

2,创建表成功后加入外键

 1 create table users(
 2    userID       int             primary key auto_increment,
 3    username     varchar(20)     not null,
 4    password     varchar(20)     not null
 5    )auto_increment = 1001;
 6    
 7 
 8 create  table userRight(
 9    ID         int            primary key  auto_increment,
10    userID     int            not null);

alter table userRight add constraint FK_constr foreign key(userID) REFERENCES users(userID);

3,删除外键约束

alter table userRight DROP foreign key FK_constr;

4,自增

1 create table users(
2    userID       int             primary key auto_increment,
3    username     varchar(20)     not null,
4    password     varchar(20)     not null
5    )auto_increment = 1001;

     主键自增在主键primary key后添加auto_increment,最后右括号后的auto_increment=1001设置初始值

5,表外自增

alter table users modify userID int auto_increment ;
//设置自增初始值
alter table users modify userID int default '1001';
//设置自增量
set auto_increment_increment=10;

 

posted @ 2018-04-18 23:59  墨染尘殇  阅读(1265)  评论(0编辑  收藏  举报