MySQL中的外键约束用于确保数据在两个表之间的引用完整性。当你在创建外键约束时,可以选择以下几种不同的约束选项:
CREATE TABLE parent (
id INT PRIMARY KEY,
name VARCHAR(255)
);
CREATE TABLE child (
id INT PRIMARY KEY,
parent_id INT,
name VARCHAR(255),
FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE CASCADE
);
CREATE TABLE parent (
id INT PRIMARY KEY,
name VARCHAR(255)
);
CREATE TABLE child (
id INT PRIMARY KEY,
parent_id INT,
name VARCHAR(255),
FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE SET NULL
);
ON DELETE SET NULL
或ON DELETE CASCADE
。CREATE TABLE parent (
id INT PRIMARY KEY,
name VARCHAR(255)
);
CREATE TABLE child (
id INT PRIMARY KEY,
parent_id INT,
name VARCHAR(255),
FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE NO ACTION
);
CREATE TABLE parent (
id INT PRIMARY KEY,
name VARCHAR(255)
);
CREATE TABLE child (
id INT PRIMARY KEY,
parent_id INT,
name VARCHAR(255),
FOREIGN KEY (parent_id) REFERENCES parent(id) ON UPDATE CASCADE
);
CREATE TABLE parent (
id INT PRIMARY KEY,
name VARCHAR(255)
);
CREATE TABLE child (
id INT PRIMARY KEY,
parent_id INT,
name VARCHAR(255),
FOREIGN KEY (parent_id) REFERENCES parent(id) ON UPDATE SET NULL
);
ON UPDATE CASCADE
或ON UPDATE SET NULL
。CREATE TABLE parent (
id INT PRIMARY KEY,
name VARCHAR(255)
);
CREATE TABLE child (
id INT PRIMARY KEY,
parent_id INT,
name VARCHAR(255),
FOREIGN KEY (parent_id) REFERENCES parent(id) ON UPDATE NO ACTION
);
在选择外键约束时,需要根据你的业务需求和数据完整性要求来决定使用哪种约束。例如,如果你希望在删除父表记录时同时删除子表中的相关记录,可以使用ON DELETE CASCADE
。如果你希望在更新父表记录时将子表中的相关外键列设置为NULL,可以使用ON UPDATE SET NULL
。