我正试图建立一个记录系统,包括监狱、监狱长、法官等。现在,我需要一张供监狱使用的桌子和一张供监狱长使用的桌子。我希望它们都能通过superintendent_id和jail_id连接起来。它们都应该是自动递增的。现在,我感到困惑的是,如果我首先创建监狱,我如何将superintendent_id放在首位,如果我将superintendent_id放在首位,如何将jail_id放在首位,因为外键有一个约束,不能为null。我的系统稍后将具有更改jail_superintendent的功能,但是在开始创建监狱时,我应该做什么呢?
CREATE TABLE JAILS
(jail_id int not null AUTO_INCREMENT,
jail_name varchar(200) not null,
capacity int not null,
jail_address varchar(200) not null,
superintendent_id int not null);
CREATE TABLE SUPERINTENDENT
(superintendent_id int not null AUTO_INCREMENT,
username varchar(20) not null, -- password is referenced from the table USERS
name char(20) not null,
jail_id int not null
sex char(1) not null,
DOB date,
DOJ date,
phone int(10),
address varchar(200),
city char(20),
state char(20),
primary key(superintendent_id),
foreign key(username) references USERS(username)
);发布于 2013-11-18 08:26:13
在两个表中都不需要jail_id和superintendent_id。如果一个监狱只能有一个警司(这似乎是合理的),那么只需使用JAILS.superintendent_id列并移除SUPERINTENDENT.jail_id列。当您想要创建一个新的监狱和一个监督时,首先创建监督,获取它的id,然后在创建监狱时使用它填充JAIL.superintendent_id字段。
CREATE TABLE JAILS
(jail_id int not null AUTO_INCREMENT,
jail_name varchar(200) not null,
capacity int not null,
jail_address varchar(200) not null,
superintendent_id int not null);
CREATE TABLE SUPERINTENDENT
(superintendent_id int not null AUTO_INCREMENT,
username varchar(20) not null, -- password is referenced from the table USERS
name char(20) not null,
sex char(1) not null,
DOB date,
DOJ date,
phone int(10),
address varchar(200),
city char(20),
state char(20),
primary key(superintendent_id),
foreign key(username) references USERS(username)
);https://stackoverflow.com/questions/20042908
复制相似问题