I have a MySQL
database with tables t1
and t2
. One of the columns in the t1
table has a foreign key for t2
.
You need to allow the foreign key column to accept null
values. There are already important data in them, rebuilding the table is not an option.
I'm using phpMyAdmin
for database manipulation
I tried the following command:
ALTER TABLE t1 MODIFY fk_t2 INT NULL DEFAULT NULL;
Itseemstowork,butwhenIopenthetable:
Consider the following, table t1 would be a sales order, and table t2 coupons, a sales order can have null or 1 coupon, and a coupon can be referencing null or N sales orders
The structure of the sales order table:
CREATE TABLE IF NOT EXISTS 'sales_order' (
'id_sales_order' INT NOT NULL AUTO_INCREMENT COMMENT '',
'fk_coupons' INT NULL DEFAULT NULL COMMENT '',
'total_price' BIGINT(20) NULL DEFAULT NULL COMMENT ''
CURRENT_TIMESTAMP COMMENT '',
PRIMARY KEY ('id_sales_order', 'fk_customer', 'fk_coupons') COMMENT '',
INDEX 'fk_sales_order_coupons1_idx' ('fk_coupons' ASC) COMMENT '',
CONSTRAINT 'fk_sales_order_coupons1'
FOREIGN KEY ('fk_coupons')
REFERENCES 'coupons' ('id_coupons')
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
PACK_KEYS = 1
The structure of the coupon table:
CREATE TABLE IF NOT EXISTS 'coupons' (
'id_coupons' INT NOT NULL AUTO_INCREMENT COMMENT '',
'coupon_name' VARCHAR(40) NULL DEFAULT NULL COMMENT '',
'discount' DECIMAL(9,4) NULL DEFAULT NULL COMMENT ''
CURRENT_TIMESTAMP COMMENT '',
PRIMARY KEY ('id_coupons') COMMENT '')
ENGINE = InnoDB