在MySQL中无法添加外键约束错误?

时间:2017-07-07 21:22:30

标签: mysql foreign-keys constraints

我一直在MySQL中遇到同样的错误,我不确定我在这里错过了什么。 我对使用MySQL很新,所以我不确定是否需要添加约束?如果我不需要约束,还有另一种方法可以定义关系吗?以下是我的语法:

    DROP TABLE IF EXISTS `art`;
    CREATE TABLE `art` (

   `art_id` INT NOT NULL,
   `art_name` VARCHAR(45) NULL,
   `artist_id` INT(11) NULL,
   `location_id` INT(11) NULL,
   `employee_id` INT(11) NULL,
   `art_received` DATE NULL,

  primary key (`art_id`),
  FOREIGN KEY (`artist_id`) REFERENCES artist(`artist_id`),
  FOREIGN KEY (`location_id`) REFERENCES location(`location_id`),
  FOREIGN KEY (`employee_id`) REFERENCES employee(`employee_id`)

  ); 

  DROP TABLE IF EXISTS `employee`;
 CREATE TABLE `employee` (

`employee_id` int(11),
`employee_userid` varchar(45),
`employee_fname` varchar(45),
`employee_lname` varchar(45),
`employee_phone` varchar (10),

primary key (`employee_id`)

); 

 DROP TABLE IF EXISTS `artist`;
 CREATE TABLE `artist` (
`artist_id` int(11),
`artist_first` varchar(45),
`artist_last` varchar(45),
`artwork_title` varchar(45),

primary key (`artist_id`)

 ); 

 DROP TABLE IF EXISTS `location`;
 CREATE TABLE `location` (
`location_id` int(11),
`location_name` varchar(45),
`start_date` date,
`end_date` date,

primary key (`location_id`)

); 

1 个答案:

答案 0 :(得分:1)

只需切换首先创建表格的顺序。当你创建  表art其他三个表仍未创建,因此它不知道哪位艺术家(artist_id),位置(location_id),员工(employee_id) 是

 DROP TABLE IF EXISTS `employee`;
 CREATE TABLE `employee` (

   `employee_id` int(11),
   `employee_userid` varchar(45),
   `employee_fname` varchar(45),
   `employee_lname` varchar(45),
   `employee_phone` varchar (10),

   primary key (`employee_id`)

); 

 DROP TABLE IF EXISTS artist;
 CREATE TABLE `artist` (
   `artist_id` int(11),
   `artist_first` varchar(45),
   `artist_last` varchar(45),
   `artwork_title` varchar(45),

   primary key (`artist_id`)

 ); 

 DROP TABLE IF EXISTS `location`;
 CREATE TABLE `location` (
   `location_id` int(11),
   `location_name` varchar(45),
   `start_date` date,
   `end_date` date,

   primary key (`location_id`)

); 



DROP TABLE IF EXISTS `art`;
CREATE TABLE `art` (

   `art_id` INT NOT NULL,
   `art_name` VARCHAR(45) NULL,
   `artist_id` int(11) NULL,
   `location_id` int(11) NULL,
   `employee_id` int(11) NULL,
   `art_received` DATE NULL,

    primary key (`art_id`),

    FOREIGN KEY (`artist_id`) REFERENCES artist(`artist_id`),
    FOREIGN KEY (`location_id`) REFERENCES location(`location_id`),
    FOREIGN KEY (`employee_id`) REFERENCES employee(`employee_id`)



); 

欢迎来到StackOverflow。如果您发现此答案或任何其他答案有用,请将其标记为解决方案。这样可以帮助社区,如果其他程序员遇到与将来一样的问题,他们可以轻松找到解决方案。