Search code examples
mysqlsqldatabasedatabase-designinnodb

Could a foreign key column has multivalue in one row from the same reference table?


I'm trying to create a database on MySQL Workbench. Is it legal if a foreign key column has a multivalue in one row? I want to do that because based on the event category the user would be allowed to see the event or not. Also, there could be multiple event categories for one event. I know that I can make a composite key to event table. But I'm wondering that can I have multivalue as a foreign key in one row?

Here is my Event table:

CREATE TABLE IF NOT EXISTS `mydb`.`EVENT` (
  `eventID` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `eventCategory` INT UNSIGNED NOT NULL,
  `name` VARCHAR(45) NOT NULL,
  `eventDescription` VARCHAR(280) NULL,
  `date` DATETIME(1) NOT NULL,
  `locationDescription` VARCHAR(45) NOT NULL,
  `regionID` INT UNSIGNED NOT NULL,
  PRIMARY KEY (`eventID`),
  INDEX `fk_EVENT_category_1_idx` (`eventCategory` ASC) VISIBLE,
  INDEX `fk_EVENT_region_1_idx` (`regionID` ASC) VISIBLE,
  CONSTRAINT `fk_EVENT_region_1`
    FOREIGN KEY (`regionID`)
    REFERENCES `mydb`.`REGION` (`regionID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_EVENT_category_1`
    FOREIGN KEY (`eventCategory`)
    REFERENCES `mydb`.`CATEGORY` (`categoryID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB

And I want to store multiple categories in one ro. I want to do that because based on those categories, some of the users wouldn't be allowed to see the event in the application.

Here is my category table:

CREATE TABLE IF NOT EXISTS `mydb`.`CATEGORY` (
  `categoryID` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `disorderID` INT UNSIGNED NOT NULL,
  `categoryDescription` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`categoryID`, `disorderID`),
  INDEX `fk_CATEGORY_disorder_1_idx` (`disorderID` ASC) VISIBLE,
  CONSTRAINT `fk_CATEGORY_disorder_1`
    FOREIGN KEY (`disorderID`)
    REFERENCES `mydb`.`DISORDERS` (`disorderID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB

Solution

  • And I want to store multiple categories in one ro. I want to do that because based on those categories, some of the users wouldn't be allowed to see the event in the application.

    No. Don't got that way. This would denormalize your schema and make simple things utterly complex later on.

    You have a many-to-many relationship between event and categories. The proper way to represent that is to create a third table, where each event/category table is stored on a separate row.

    Something like:

    create table event_categories (
        event_id int not null,
        category_id int not null,
        primary key (event_id, category_id),
        foreign key(event_id) references event(event_id),
        foreign key(category_id) references category(category_id),
    );