1ALTER TABLE orders
2ADD
3FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE;
1-- On Create
2CREATE TABLE tableName (
3 ID INT,
4 SomeEntityID INT,
5 PRIMARY KEY (ID),
6 FOREIGN KEY (SomeEntityID)
7 REFERENCES SomeEntityTable(ID)
8 ON DELETE CASCADE
9);
10
11-- On Alter, if the column already exists but has no FK
12ALTER TABLE
13 tableName
14ADD
15 FOREIGN KEY (SomeEntityID) REFERENCES SomeEntityTable(ID) ON DELETE CASCADE;
16
17 -- Add FK with a specific name
18 -- On Alter, if the column already exists but has no FK
19ALTER TABLE
20 tableName
21ADD CONSTRAINT fk_name
22 FOREIGN KEY (SomeEntityID) REFERENCES SomeEntityTable(ID) ON DELETE CASCADE;
1CREATE TABLE parent (
2 id INT NOT NULL,
3 PRIMARY KEY (id)
4) ENGINE=INNODB;
5
6CREATE TABLE child (
7 id INT,
8 parent_id INT,
9 INDEX par_ind (parent_id),
10 FOREIGN KEY (parent_id)
11 REFERENCES parent(id)
12 ON DELETE CASCADE
13) ENGINE=INNODB;
1ALTER TABLE `TABLE_NAME`
2ADD COLUMN `COLUMN_NAME` BIGINT(20) UNSIGNED NULL DEFAULT NULL AFTER `AFTER_COLUMN_NAME`,
3ADD FOREIGN KEY `FOREIGN_RELATION_NAME`(`COLUMN_NAME`) REFERENCES `FOREIGN_TABLE`(`FOREIGN_COLUMN`) ON UPDATE SET NULL ON DELETE SET NULL
1ALTER TABLE tryholpz_demo07.core_modules
2ADD COLUMN belongs_to_role INT,
3ADD FOREIGN KEY core_modules(belongs_to_role) REFERENCES role_specific_modules_info(id) ON DELETE CASCADE