Why am I getting this error: "Cannot add foreign key constraint."

时间:2015-07-31 20:03:06

标签: mysql foreign-keys ddl

When executing the following SQL statements it gives me an error such as "Error 1215: Cannot add foreign key constraint" at the first table: process.

This is my SQL code.

CREATE TABLE process(
  idp VARCHAR(36) NOT NULL,
  idc VARCHAR(36) NOT NULL,
  name VARCHAR(255) NOT NULL,
  description TEXT NULL,
  provider TEXT NULL,
  PRIMARY KEY(idp),
  FOREIGN KEY (idc) REFERENCES clients(idc)
  ON DELETE CASCADE
) ENGINE=INNODB;

CREATE TABLE tag_group (
  idtg VARCHAR(36) NOT NULL,
  idp VARCHAR(36) NOT NULL,
  name VARCHAR(255) NOT NULL,
  description TEXT NULL,
  ttl TEXT NULL,
  PRIMARY KEY(idtg),
  FOREIGN KEY (idp) REFERENCES process(idp)
  ON DELETE CASCADE
) ENGINE=INNODB;

CREATE TABLE clients (
  idc VARCHAR(36) NOT NULL,
  name VARCHAR(255) NOT NULL,
  company VARCHAR(255) NOT NULL,
  address VARCHAR(255) NULL,
  phone VARCHAR(45) NULL,
  fax VARCHAR(255) NULL,
  website VARCHAR(255) NULL,
  PRIMARY KEY(idc)
) ENGINE=INNODB;

CREATE TABLE users (
  idu VARCHAR(36) NOT NULL,
  idc VARCHAR(36) NOT NULL,
  title VARCHAR(36) NULL,
  firs_name VARCHAR(255) NOT NULL,
  last_name VARCHAR(255) NOT NULL,
  email VARCHAR(255) NULL,
  password VARCHAR(255) NOT NULL,
  country VARCHAR(255) NULL,
  city VARCHAR(255) NULL,
  telephone VARCHAR(255) NULL,
  is_agent BOOLEAN NOT NULL,
  last_login TIMESTAMP NULL,
  timeout TIMESTAMP NULL,
  timeout_enabled BOOLEAN NULL,
  preferred_language VARCHAR(36) NOT NULL,
  PRIMARY KEY(idu),
  FOREIGN KEY (idc) REFERENCES clients(idc)
  ON DELETE CASCADE
) ENGINE=INNODB;

2 个答案:

答案 0 :(得分:2)

Try creating all the Primary keys first, then add the FK constraint. Odds are the FK constraint won't add because it's being linked to a PK that hasn't been made yet.

答案 1 :(得分:0)

CREATE TABLE clients (
 idc VARCHAR(36) NOT NULL,
 name VARCHAR(255) NOT NULL,
 company VARCHAR(255) NOT NULL,
 address VARCHAR(255) NULL,
 phone VARCHAR(45) NULL,
 fax VARCHAR(255) NULL,
 website VARCHAR(255) NULL,
 PRIMARY KEY(idc)
) ENGINE=INNODB;

CREATE TABLE process(
 idp VARCHAR(36) NOT NULL,
 idc VARCHAR(36) NOT NULL,
 name VARCHAR(255) NOT NULL,
 description TEXT NULL,
 provider TEXT NULL,
 PRIMARY KEY(idp),
 FOREIGN KEY (idc) REFERENCES clients(idc)
 ON DELETE CASCADE
) ENGINE=INNODB;

.........