简体   繁体   中英

Cannot add foreign key constraint SQL when building schema

I'm taking a intro to database class right now. For a homework assignment I was given a piece of SQL code and told to just run some queries and give the results back. The problem is I can't even build the schema given with the code my teacher gave me. Here is this code:

CREATE TABLE emp (
  name char(15),
  dno int,
  FOREIGN KEY (dno) REFERENCES dept(dno)
  ON DELETE SET NULL
  ON UPDATE CASCADE
  );

CREATE TABLE dept (
  dno int,
  location char(30)
 );

INSERT INTO emp(name,dno) VALUES
("Tom",111),
("Mary",111),
("Jack",222),
("Henry",222);

INSERT INTO dept(dno, location) VALUES
(111,"Irvine"),
(222,"LA"),
(333,"SF");

When this runs I get a error saying Cannot add foreign key constraint . I tried doing this via MySQL workbench and SQL Fiddle, both of which produce the same error. I don't really know whats wrong with the code given to me though and after looking online, couldn't seem to see anything obvious.

It may be part of the exercise for you to figure this out. However, assuming that it is not, here are important observations:

  • The foreign key reference should be to a primary key, and neither table has primary keys.
  • The table being referenced has to be defined before it can be referred to.

You can work on fixing these problems. Here is a SQL Fiddle with the right definitions.

The definition of the first table (emp) has a reference to a table that has not yeat been created (dept).You have to create first 'dept' to create a foreign key of it into another table.

Execute the queries in this order:

CREATE TABLE dept (
  dno int,
  location char(30)
 );

CREATE TABLE emp (
  name char(15),
  dno int,
  FOREIGN KEY (dno) REFERENCES dept(dno)
  ON DELETE SET NULL
  ON UPDATE CASCADE
  );

INSERT INTO emp(name,dno) VALUES
("Tom",111),
("Mary",111),
("Jack",222),
("Henry",222);

INSERT INTO dept(dno, location) VALUES
(111,"Irvine"),
(222,"LA"),
(333,"SF");

尝试:CONSTRAINT dno_fk外键(dno)参考DEPT(dno)删除级联

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM