在 MySQL 中创建外键

Creating foreign key in MySQL

我正在尝试使用 MySQL workbench 在 MySQL 中创建外键。但是有错误

$ Executing:
ALTER TABLE `project_course`.`attendance` 
ADD CONSTRAINT `FK_Student`
  FOREIGN KEY ('idStudent')
  REFERENCES `project_course`.`student` ('userid')
  ON DELETE NO ACTION
  ON UPDATE NO ACTION;

Operation failed: There was an error while applying the SQL script to the database.
ERROR 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''idStudent')
  REFERENCES `project_course`.`student` ('userid')
  ON DELETE NO A' at line 3
SQL Statement:
ALTER TABLE `project_course`.`attendance` 
ADD CONSTRAINT `FK_Student`
  FOREIGN KEY ('idStudent')
  REFERENCES `project_course`.`student` ('userid')
  ON DELETE NO ACTION
  ON UPDATE NO ACTION

问题出在引号上(在 PC 上它位于 Enter 键周围)。您使用了它们而不是反引号(在 PC 上它位于 Esc 键下)。

ALTER TABLE `project_course`.`attendance` 
ADD CONSTRAINT `FK_Student`
  FOREIGN KEY (`idStudent`) # Change them here around `idStudent` 
  REFERENCES `project_course`.`student` (`userid`) # and here around `userid` 
  ON DELETE NO ACTION
  ON UPDATE NO ACTION;

Musa 的回答是正确的,但解释有不足之处。这是一个更好的。

您在外键和引用子句中对列名使用了单引号字符。单引号表示 MySQL 中的字符串,但是在这些位置需要列引用,即标识符。在您的情况下,您根本不需要引号,因为在不使用引号 (see the identifier rules for MySQL) 时允许标识符中的所有字符。但是,如果您根据用户输入或其他生成的数据创建查询,最好始终引用(以避免 sql 注入并确保无论使用的引用名称如何都能正常工作)。

通常引用意味着将标识符放在反引号中,这总是有效的。或者,您可以使用 "double quotes",但前提是您当前的 SQL 模式包含 ANSI_QUOTES 模式。否则双引号也表示字符串(如单引号)。如果您不能确保设置 ANSI_QUOTES 模式,使用双引号有点冒险。

将此代码复制并粘贴到您的 Mysql 脚本编辑器 和 运行 中。您将有两个表 categoriesproducts 这些表具有 cat_id 作为 外键.

CREATE DATABASE IF NOT EXISTS dbdemo;

USE dbdemo;

CREATE TABLE categories(
   cat_id int not null auto_increment primary key,
   cat_name varchar(255) not null,
   cat_description text
) ENGINE=InnoDB;

CREATE TABLE products(
   prd_id int not null auto_increment primary key,
   prd_name varchar(355) not null,
   prd_price decimal,
   cat_id int not null,
   FOREIGN KEY fk_cat(cat_id)
   REFERENCES categories(cat_id)
   ON UPDATE CASCADE
   ON DELETE RESTRICT
)ENGINE=InnoDB;