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
。