2017-01-12 16 views
0

父表team_entrantMySQL的外鍵錯誤1215,即使這兩個colums是相同類型的並且是NOT NULL

CREATE TABLE IF NOT EXISTS `team_entrant` (
    `entrant_number` tinyint(4) NOT NULL, 
    `qualifying_position` tinyint(4) NOT NULL, 
    `qualifying_time` time(3) NOT NULL, 
    `grid_position` tinyint(4) DEFAULT NULL, 
    `best_race_time` datetime DEFAULT NULL, 
    `final_position` tinyint(4) DEFAULT NULL, 
    `dnf_reason` varchar(45) DEFAULT NULL, 
    `team_id` int(11) NOT NULL, 
    `competition_year` date NOT NULL, 
    PRIMARY KEY (`entrant_number`), 
    KEY `fk_team_entrant_team1_idx` (`team_id`), 
    CONSTRAINT `fk_team_entrant_team1` FOREIGN KEY (`team_id`) REFERENCES `team` (`team_id`) ON DELETE NO ACTION ON UPDATE NO ACTION 
) ENGINE=InnoDB DEFAULT CHARSET=utf8; 

子表/關聯表entrant_drivers

CREATE TABLE IF NOT EXISTS `entrant_drivers` (
    `entrant_number` tinyint(4) NOT NULL, 
    `competition_year` date NOT NULL, 
    `driver_id` int(11) NOT NULL, 
    PRIMARY KEY (`entrant_number`,`competition_year`,`driver_id`), 
    CONSTRAINT `ed_entrant_fk` FOREIGN KEY (`entrant_number`) REFERENCES `team_entrant` (`entrant_number`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8; 

當時team_entrant列competition_year不存在。

HeidiSQL拒絕執行以下代碼:

ALTER table entrant_drivers ADD CONSTRAINT ed_comp_year_fk FOREIGN KEY (competition_year) REFERENCES team_entrant(competition_year); 

SQL錯誤(1215):無法添加外鍵約束

外來表,driver涉及的關聯表:

-- Dumping structure for table 99_lemans_db1.driver 
CREATE TABLE IF NOT EXISTS `driver` (
    `driver_id` int(11) NOT NULL, 
    `driver_name` varchar(64) NOT NULL, 
    `driver_nationality` varchar(32) NOT NULL, 
    `driver_birth_day` date NOT NULL, 
    `driver_best_previous_finish_class` varchar(8) DEFAULT NULL, 
    `driver_best_previous_finish_position` tinyint(4) DEFAULT NULL, 
    `team_entrant_id` int(11) NOT NULL, 
    PRIMARY KEY (`driver_id`,`team_entrant_id`), 
    KEY `fk_driver_team_entrant1_idx` (`team_entrant_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8; 

任何援助將b e讚賞。

回答

0

父列必須被指定爲索引/主鍵。

team_entrant應該由複合主鍵(參賽者號碼,比賽年份)組成。

相關問題