Home > database >  What does `REFERENCES` do in sql?
What does `REFERENCES` do in sql?

Time:03-07

I'm trying to write a 1-many schema with simple example. I have one table books mapping to many tags. (see fiddle links below)

What I want is for the tags table to have a foreign key to books table. I think I have managed this:

 
CREATE TABLE IF NOT EXISTS `books` (
  `id` int(6) unsigned NOT NULL,
  `book_name` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
 
 
CREATE TABLE IF NOT EXISTS `tags` (
  `tag_id` int(6) unsigned NOT NULL,
  `tag` varchar(100) NOT NULL,
  `book_id` int(6)  unsigned NOT NULL,
  PRIMARY KEY (`tag_id`)
);
 

I don't understand the difference between:

  `book_id` int(6)  unsigned NOT NULL,

and

  `book_id` int(6)  unsigned NOT NULL REFERENCES `books`(`id`),

Both compile fine and work with inner joins

http://sqlfiddle.com/#!9/612337/1

http://sqlfiddle.com/#!9/2043b8/3

So what's the difference between the snippets?

CodePudding user response:

https://dev.mysql.com/doc/refman/8.0/en/ansi-diff-foreign-keys.html says:

MySQL parses but ignores “inline REFERENCES specifications” (as defined in the SQL standard) where the references are defined as part of the column specification. MySQL accepts REFERENCES clauses only when specified as part of a separate FOREIGN KEY specification.

This syntax creates a column; it does not create any sort of index or key.

When used in this fashion, the REFERENCES clause is not displayed in the output of SHOW CREATE TABLE or DESCRIBE:

That is, the following creates the column book_id but not a foreign key constraint:

`book_id` int unsigned NOT NULL REFERENCES `books`(`id`),

You must do it this way:

`book_id` int unsigned NOT NULL,
FOREIGN KEY (book_id) REFERENCES `books`(`id`),

The decision was made years ago to skip implementing inline REFERENCES as a column option. You would have to use the separate line for the FOREIGN KEY constraint anyway if you made a foreign key for two or more columns. The inline REFERENCES as part of a column definition is just a convenient short-cut syntax.

The fact that the syntax is parsed but ignored has been reported as a bug since at least 2004, but never fixed:

But because of MySQL pluggable storage engine architecture, it's difficult to fix this bug. SQL syntax parsing is handled independently of the storage engine, but implementation of constraints is handled within the storage engine. The SQL parser must allow the syntax, because it doesn't know whether the feature will be ignored or supported by a given storage engine.

  • Related