在mysql中删除set null创建表

Rav*_*utt 0 mysql

我要创建一个名为patientmedicinecategory的表.如下: -

 CREATE TABLE patientmedicinecategory
 (
 pmc         int(11) NOT NULL AUTO_INCREMENT,
 patient_id  int(11) NOT NULL,
 med_id      int(3) NOT NULL,
 cat_id      int(3) NOT NULL,
 testname    varchar(100) NOT NULL,

 PRIMARY KEY(pmc),
 UNIQUE KEY(patient_id, med_id,cat_id,testname),
 FOREIGN KEY(patient_id) REFERENCES patient(patient_id) ON UPDATE CASCADE ON DELETE    
 CASCADE,
 FOREIGN KEY(med_id) REFERENCES medicine(med_id) ON UPDATE CASCADE ON DELETE CASCADE,
 FOREIGN KEY(cat_id) REFERENCES category(cat_id) ON UPDATE CASCADE ON DELETE SET NULL
 )ENGINE=InnoDB;
Run Code Online (Sandbox Code Playgroud)

我的病人表是: -

  CREATE TABLE patient
  (
  patient_id    int NOT NULL AUTO_INCREMENT,
  salutation    ENUM('Mr.','Mrs.','Miss.','Dr.') NOT NULL,
  name      varchar(50) NOT NULL,
  email_id  varchar(100),
  year      int(4) NOT NULL,
  month     int(3),
  day       int(3),
  sex       ENUM('M','F') NOT NULL,
  contactno         varchar(50),    

  PRIMARY KEY(patient_id)
  )ENGINE=InnoDb;
Run Code Online (Sandbox Code Playgroud)

药桌是: -

  CREATE TABLE medicine
  (
  med_id  int(3) NOT NULL,
  name    varchar(40) NOT NULL,

  PRIMARY KEY (med_id)
  )ENGINE=InnoDB;
Run Code Online (Sandbox Code Playgroud)

类别表是: -

  CREATE TABLE category
  (
  cat_id    int(3) NOT NULL,
  name      varchar(20) NOT NULL,

  PRIMARY KEY (cat_id)
  )ENGINE=InnoDB;
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试创建它时,它会给出错误: -

   ERROR 1005 (HY000): Can't create table 'nutech3.patientmedicinecategory' (errno: 150)
Run Code Online (Sandbox Code Playgroud)

我已经尝试了很多但是没有成功.请帮我 .提前致谢

Álv*_*lez 8

如果您以root身份登录并运行,SHOW ENGINE INNODB STATUS您将看到确切的错误消息是这样的:

------------------------
LATEST FOREIGN KEY ERROR
------------------------
130405 11:55:42 Error in foreign key constraint of table test/patientmedicinecategory:
FOREIGN KEY(cat_id) REFERENCES category(cat_id) ON UPDATE CASCADE ON DELETE SET NULL
 )ENGINE=InnoDB:
You have defined a SET NULL condition though some of the
columns are defined as NOT NULL.
Run Code Online (Sandbox Code Playgroud)

这是违规行:

FOREIGN KEY(cat_id) REFERENCES category(cat_id) ON UPDATE CASCADE ON DELETE SET NULL
Run Code Online (Sandbox Code Playgroud)

MySQL无法生成patientmedicinecategory.cat_idNULL,因为它以这种方式定义:

cat_id      int(3) NOT NULL,
Run Code Online (Sandbox Code Playgroud)

您的选择是:

  • 允许cat_idNULL
  • 设置不同的ON DELETE条件