Allow null value in relationship field

Asked

Viewed 1,275 times

1

I have a database MySQL with tables t1 and t2. One of the columns in the table t1 has a foreign key to t2.

You need to allow the foreign key column to accept values null. Important data already exists in them, recreating the table is not an option.

I’m using the phpMyAdmin for manipulation of the database

I tried the following command:

ALTER TABLE t1 MODIFY fk_t2 INT NULL DEFAULT NULL;

inserir a descrição da imagem aqui

It seems to work, but when I open the table:

inserir a descrição da imagem aqui


Understand the following, the table t1 would be a sales order, and the table t2 coupons, a sales order may have null or 1 coupon, and a coupon may 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
  • The problem you have now is should there always be a valid coupon (ie it exists in the table of cumpons) for a purchase? The suggestion I have is to register a coupon with the id zero for example and give the description of 'without cumpom' or 'sale without discount' and always associate this id with purchases without discount/coupon. Of course assess whether this is appropriate for your case.

  • The problem is that I would like to allow null value on that coupon rs, there is a way?

  • This is one of the possibilities that I initially thought @rray, but if possible wanted to opt for null value

1 answer

2


By the structure of your table sales_order, the column fk_coupons is part of the primary key.

You cannot have value-less primary key (null).

If you really need it and you can take it fk_coupons of PK, you can:

ALTER TABLE SALES_ORDER DROP PRIMARY KEY

And then:

ALTER TABLE SALES_ORDER ADD PRIMARY KEY (id_sales_order, fk_customer)
  • Your answer was not the solution to the problem, but it made me see what was the problem rs

  • Good! The important thing is to help. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.