SQL外键约束语法

时间:2013-04-17 10:51:23

标签: mysql sql foreign-keys

我无法导入我的数据库,因为我错误地配置了我的外键。有人可以告诉我我做错了什么吗?

  CREATE TABLE `candidats` (
  `id_candidats` varchar(20) NOT NULL DEFAULT '1',
  `affiche_candidat` varchar(50) DEFAULT NULL,
  `film_id_film` tinyint(1) unsigned NOT NULL,
  `categories_id_categorie` tinyint(2) unsigned NOT NULL,
  `ecole_id_ecole` tinyint(3) unsigned NOT NULL,
  `email_candidat` varchar(75) DEFAULT NULL,
  `password_candidat` varchar(20) DEFAULT NULL,
  `nom_candidat` varchar(50) DEFAULT NULL,
  `prenom_candidat` varchar(50) DEFAULT NULL,
  `datenaiss` date DEFAULT NULL,
  `titre` varchar(50) DEFAULT 'sans-titre',
  `description` mediumblob,
  `approuvee` tinyint(1) NOT NULL DEFAULT '0',
  `abus` tinyint(1) NOT NULL DEFAULT '0',
  `votes_candidat` mediumint(4) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id_candidats`),
  KEY `candidats_FKIndex4` (`film_id_film`),
  KEY `candidats_FKIndex3` (`ecole_id_ecole`),
  KEY `candidats_FKIndex2` (`categories_id_categorie`),
  KEY `film_id_film` (`film_id_film`),
  KEY `ecole_id_ecole` (`ecole_id_ecole`),
  KEY `categories_id_categorie` (`categories_id_categorie`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;



CREATE TABLE `categories` (
  `id_categorie` tinyint(2) unsigned NOT NULL AUTO_INCREMENT,
  `nom_categorie` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id_categorie`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;



CREATE TABLE `ecole` (
  `id_ecole` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `nom_ecole` varchar(100) DEFAULT NULL,
  `nom_referent` varchar(50) DEFAULT NULL,
  `email_ecole` varchar(50) DEFAULT NULL,
  `tel_ecole` varchar(13) DEFAULT NULL,
  PRIMARY KEY (`id_ecole`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=15 ;



CREATE TABLE `films` (
  `id_films` tinyint(1) unsigned NOT NULL AUTO_INCREMENT,
  `nom_films` varchar(25) NOT NULL,
  `class_films` varchar(12) NOT NULL,
  PRIMARY KEY (`id_films`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;


ALTER TABLE `candidats`
  ADD CONSTRAINT `candidats_ibfk_1` FOREIGN KEY (`ecole_id_ecole`) REFERENCES `ecole` (`id_ecole`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `candidats_ibfk_2` FOREIGN KEY (`categories_id_categorie`) REFERENCES `categories` (`id_categorie`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `candidats_ibfk_3` FOREIGN KEY (`film_id_film`) REFERENCES `films` (`id_films`) ON DELETE NO ACTION ON UPDATE NO ACTION;

1 个答案:

答案 0 :(得分:0)

事实证明,我已经将0插入了candaidat桌子的电影栏中。由于0不是可能的ID号,因此会引发错误。