MySQL中的外鍵約束用于確保數(shù)據(jù)在兩個(gè)表之間的引用完整性。當(dāng)你在創(chuàng)建外鍵約束時(shí),可以選擇以下幾種不同的約束選項(xiàng):
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
);
在選擇外鍵約束時(shí),需要根據(jù)你的業(yè)務(wù)需求和數(shù)據(jù)完整性要求來(lái)決定使用哪種約束。例如,如果你希望在刪除父表記錄時(shí)同時(shí)刪除子表中的相關(guān)記錄,可以使用ON DELETE CASCADE
。如果你希望在更新父表記錄時(shí)將子表中的相關(guān)外鍵列設(shè)置為NULL,可以使用ON UPDATE SET NULL
。