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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM