CREATE TABLE location (
uid int not null auto_increment primary key,
name varchar(255) NOT NULL,
`state_uid` int not null,
FOREIGN KEY location(state_uid)
REFERENCES state(uid)
ON UPDATE CASCADE
ON DELETE RESTRICT,
`city_uid` int not null,
FOREIGN KEY location(city_uid)
REFERENCES city(uid)
ON UPDATE CASCADE
ON DELETE RESTRICT,
`area_uid` int not null,
FOREIGN KEY location(area_uid)
REFERENCES area(uid)
ON UPDATE CASCADE
ON DELETE RESTRICT
);
答案 0 :(得分:0)
CREATE TABLE location (
uid int not null auto_increment primary key,
name varchar(255) NOT NULL,
state_uid int not null,
city_uid int not null,
area_uid int not null,
CONSTRAINT fk_state FOREIGN KEY (state_uid) REFERENCES state(uid) ,
CONSTRAINT fk_city FOREIGN KEY (city_uid) REFERENCES city(uid) ,
CONSTRAINT fk_area FOREIGN KEY (area_uid) REFERENCES area(uid)
);
尝试此查询
确保父表存在
答案 1 :(得分:0)
你的版本几乎就好了。问题是外键引用中的location
。
您对级联内容或列的排序没有任何问题。所以,这有效:
CREATE TABLE location (
uid int not null auto_increment primary key,
name varchar(255) NOT NULL,
`state_uid` int not null,
FOREIGN KEY (state_uid) REFERENCES state(uid) ON UPDATE CASCADE ON DELETE RESTRICT,
`city_uid` int not null,
FOREIGN KEY (city_uid) REFERENCES city(uid) ON UPDATE CASCADE ON DELETE RESTRICT,
`area_uid` int not null,
FOREIGN KEY (area_uid) REFERENCES area(uid) ON UPDATE CASCADE ON DELETE RESTRICT
);
Here是一个SQL小提琴。
请注意,在列定义之后放置显式foreign key
(和其他约束)通常是传统的,没有规则或标准。实际上,大多数数据库都支持内联外键定义。但是,MySQL没有。