Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between references and foreign key

here are two declaration in sql

create table bookAdoption
(   
    courseId int,
    sem int,
    isbn int,
    PRIMARY KEY(courseId, sem, isbn),       
    FOREIGN KEY(courseId) REFERENCES course(courseId),
    FOREIGN KEY(sem) REFERENCES enroll(sem)
);

and the other one

CREATE TABLE bookAdoption
(
    courseId INT REFERENCES course(courseId) ,
    sem INT REFERENCES enroll(sem),
    isbn INT REFERENCES text1(isbn),
    PRIMARY KEY(courseId, sem, isbn)

);

what is the between using only references keyword

and using both references and foreign keyword both together screenshot

like image 627
tiger Avatar asked Feb 03 '13 13:02

tiger


2 Answers

You can't use the REFERENCES without a foreign key constraint, as quoted from the MySQL Documentation, FOREIGN KEY Constraints:

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.

like image 149
Mahmoud Gamal Avatar answered Sep 22 '22 15:09

Mahmoud Gamal


A FOREIGN KEY can only reference a column that is UNIQUE.

In practice we ussualy add foreign key constraints to primary keys, and we say that the FK references the PK. But it is possible to add such a constraint with any UNIQUE column(s).

In order for this to work SQL syntax requires you to:

  • declare a foreign key
  • tell it what to reference
like image 40
Bogdan Gavril MSFT Avatar answered Sep 21 '22 15:09

Bogdan Gavril MSFT