REFERENCES是否必须与外键一起使用

时间:2016-03-04 23:19:49

标签: mysql sql foreign-key-relationship

友谊表仅使用没有FOREIGN KEY关键字的REFERENCES。没有与Foreign Key关键字耦合是一个错误,还是有效并代表另一种语义?友谊表应该包含任意一对两个朋友的ID。

Create table Student (
id int NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id)
);

Create table Book (
id int NOT NULL AUTO_INCREMENT,
student_id int NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (student_id)
  REFERENCES Student(id)
  ON DELETE CASCADE
);

Create table Friendship (
  id_from int NOT NULL REFERENCES Student(id),
  id_to int NOT NULL REFERENCES Student(id), 
  PRIMARY KEY (id_from, id_to) 
);

我在MySql中创建了3个表,并在其中插入了一些数据,我可以进行搜索,例如“正确查找”John的所有朋友。

但是我不太确定REFERENCES是否可以像这样单独使用作为外键约束。

编辑:

按照评论的建议,我将友谊修改为以下内容:

Create table Friendship (
  id_from int NOT NULL,
  id_to int NOT NULL, 
  PRIMARY KEY (id_from, id_to)
  FOREIGN KEY (id_from) REFERENCES Student(id)
  FOREIGN KEY (id_to) REFERENCES Student(id)
);

但是现在我在创建此表时收到语法错误:

Create table Friendship (
    ->   id_from int NOT NULL,
    ->   id_to int NOT NULL, 
    ->   PRIMARY KEY (id_from, id_to)
    ->   FOREIGN KEY (id_from) REFERENCES Student(id)
    ->   FOREIGN KEY (id_to) REFERENCES Student(id)
    -> );
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'FOREIGN KEY (id_from) REFERENCES Student(id)
  FOREIGN KEY (id_to) REFERENCES Student(' at line 5

0 个答案:

没有答案