MySQL表主/外键使id跟随

时间:2018-03-29 06:28:05

标签: mysql

考虑这些模式

create table users (

    id int auto_increment not null primary key,

    username varchar(256) not null,

    password varchar(256) not null

);

create table grades (

    id int auto_increment not null,

    username varchar(256) not null,

    assignmentName varchar(256) not null,

    mark int,

    foreign key(id) references users(id)

);

考虑这个用户表:

id   username   password
1    a          x 
2    b          x
3    c          x

我希望成绩表具有相同的主要 - 用户名关系,以便下面的成绩表可以轻松存在,

id   username   assignmentname   mark
1    a          a1               10 
1    a          a2               20
3    c          a1               30

正如您所看到的,ID并未因用户而发生变化。无论如何我能做到吗?我目前的方式不起作用。

INSERT表:

insert into users values 

(NULL, "a", "x"),
(NULL, "b", "x"),
(NULL, "c", "x");


insert into grades values

(NULL, "a", "a1", 10),
(NULL, "a", "a2", 20),
(NULL, "c", "a1", 30)

1 个答案:

答案 0 :(得分:0)

你不能拥有“身份证”。它同时自动增量和外键,你需要改变你的CREATE语句:

create table grades (
    grades_id int not null auto_increment,    
    id int not null,    
    username varchar(256) not null,    
    assignmentName varchar(256) not null,    
    mark int,  
    PRIMARY KEY (`grades_id`),  
    foreign key(id) references users(id)    
);

您可以使用用户名作为外键:

create table grades (
    id int not null auto_increment,    
    username varchar(256) not null,    
    assignmentName varchar(256) not null,    
    mark int,  
    PRIMARY KEY (`id`),  
    foreign key(username) references users(username)    
);