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;
1
2
3
4
5 CREATE TABLE products(
6 productId INT AUTO_INCREMENT PRIMARY KEY,
7 productName varchar(100) not null,
8 categoryId INT NOT NULL,
9 CONSTRAINT fk_category
10 FOREIGN KEY (categoryId)
11 REFERENCES categories(categoryId)
12 ON UPDATE CASCADE
13 ON DELETE CASCADE
14) ENGINE=INNODB;
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
1ALTER TABLE ordenes ADD ticket VARCHAR(50) NOT NULL;
2ALTER TABLE ordenes ADD CONSTRAINT fk_ticket FOREIGN KEY (ticket) REFERENCES tickets(ticket);
3// I'm Horrible Hyena
1ALTER TABLE ordenes ADD ticket VARCHAR(50) NOT NULL;
2ALTER TABLE ordenes ADD CONSTRAINT fk_ticket FOREIGN KEY (ticket) REFERENCES tickets(ticket);
3