Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 views
in Technique[技术] by (71.8m points)

mysql - Difference between using REFERENCES with and without FOREIGN KEY?

Basically I'd like to know the difference between using REFERENCES with or without a foreign key.

I have these 2 examples:

CREATE TABLE Employee 
(
     id        INT,
     name      VARCHAR(50),
     birthYear INT,
     boss      INT REFERENCES Employees(id),
     worksAt   INT NOT NULL REFERENCES Department(id) ON DELETE CASCADE,
     PRIMARY KEY (id,worksAt)
);

Example 2:

CREATE TABLE Department 
(
      id                INT PRIMARY KEY,
      name              VARCHAR(50),
      numberOfEmployees INT,
      location          INT NOT NULL,
      country           INT NOT NULL,
      manager           INT,
      FOREIGN KEY (location,country) REFERENCES Location(locId,countryId),
      UNIQUE KEY (manager)
);

What I'm asking here is why does the second example use the FOREIGN KEY keyword while the first one merely uses REFERENCES.

Also, the first one seems to reference itself (I think the s in Employees is a mistake) If so, why does it use REFERENCES if it's referencing itself?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Congratulations! You've stumbled upon one of the weirder quirks of MySQL. The first syntax does absolutely nothing. It's silently, yes, silently ignored.

Furthermore, InnoDB does not recognize or support “inline REFERENCES specifications” (as defined in the SQL standard) where the references are defined as part of the column specification. InnoDB accepts REFERENCES clauses only when specified as part of a separate FOREIGN KEY specification. For other storage engines, MySQL Server parses and ignores foreign key specifications.

It's a little under halfway down the create table documentation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...