【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;

 

转载于:https://www.cnblogs.com/purplelavender/p/8878673.html

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值