表用户
create table users(
id int(11) primary key auto_increment,
unique_id varchar(23) not null unique,
name varchar(50) not null,
cname varchar(50) not null,
email varchar(100) not null unique,
encrypted_password varchar(80) not null,
salt varchar(10) not null,
created_at datetime,
updated_at datetime null
);
表行为
CREATE TABLE behaviours (
id int(2) AUTO_INCREMENT PRIMARY KEY,
bName varchar(100) NOT NULL
);
表格severytys
CREATE TABLE severitys (
id int(2) AUTO_INCREMENT PRIMARY KEY,
severity varchar(10) NOT NULL
);
这里显示错误:
CREATE TABLE child_behaviours(
id int(11) primary key auto_increment,
name varchar(50) not null,
cname varchar(50) not null,
bName varchar(100) NOT NULL,
severity varchar(10) NOT NULL,
start_at datetime,
stop_at datetime null,
FOREIGN KEY (id) REFERENCES users(id),
FOREIGN KEY (bName) REFERENCES behaviours(bName),
FOREIGN KEY (severity) REFERENCES severitys(severity)
);
真的很想回答这个问题
答案 0 :(得分:1)
构建外键时必须引用主键
CREATE TABLE child_behaviours(
userId int not null,
behaviourId int NOT NULL,
severityId int NOT NULL,
start_at datetime not null,
stop_at datetime,
FOREIGN KEY (userId) REFERENCES users(id),
FOREIGN KEY (behaviourId) REFERENCES behaviours(id),
FOREIGN KEY (severityId) REFERENCES severitys(id)
);
答案 1 :(得分:1)
您只能在UNIQUE和NOT NULL的列上创建FK。这通常(但不总是)是引用表的主键。
如果您引用除PK之外的任何其他内容,您需要一个非常好的理由。
(我甚至还要补充一点,你需要一个非常好的理由来使用INT以外的任何东西或一对INT作为PK ......)
现在,child_behaviours有几个错误:
此外,使用“id”列存在一般错误。请将它们称为“user_id”,“severity_id”等,然后在引用中将它们称为相同。这将使您的生活更轻松,并避免像:
SELECT foo.id AD foo_id, bar.id AS bar_id FROM foo JOIN bar ON ...