Innodb does not accept foreign key

2019-08-30 11:01发布

问题:

We cannot run the query below. We have another table named "person" and it has a primary key person_id. As you can see, we are trying to get this column as our (customers table's) foreign key. phpMyAdmin returns #1064 syntax error. What's going wrong here?

CREATE  TABLE IF NOT EXISTS `resort`.`customers` (
  `person_id` VARCHAR(45) NOT NULL ,
  `cid` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
  UNIQUE INDEX `person_id_UNIQUE` (`cid` ASC) ,
  PRIMARY KEY (`person_id`) ,
  UNIQUE INDEX `person_id_UNIQUE` (`person_id` ASC) ,
  CONSTRAINT `person_id`
    FOREIGN KEY ()
    REFERENCES `resort`.`person` ()
    ON DELETE CASCADE
    ON UPDATE CASCADE)
ENGINE = InnoDB

By the way, this query is generated by Oracle's MySQL Workbench.

回答1:

You need to include the columns in the constraint definition:

CONSTRAINT person_id
  FOREIGN KEY ()
  REFERENCES resort.person()
  ON DELETE CASCADE
  ON UPDATE CASCADE

should be:

CONSTRAINT fk_person_id
  FOREIGN KEY (person_id)
  REFERENCES resort.person (id)
  ON DELETE CASCADE
  ON UPDATE CASCADE