简体   繁体   English

mysql 1215无法添加外键约束

[英]mysql 1215 cannot add foreign key constraint

I have a SQL script that yields me the error: 我有一个SQL脚本,让我产生错误:

DROP TABLE IF EXISTS test_db.users
;

CREATE TABLE users
(
  id SERIAL, 
  username VARCHAR(20) NOT NULL,
  password VARCHAR(20) NOT NULL,
  PRIMARY KEY (id)
);

DROP TABLE IF EXISTS test_db.comments
;

CREATE TABLE comments
(
  id SERIAL,
  content varchar(255) NOT NULL,
  userId BIGINT(20) NOT NULL,
  CONSTRAINT fk_comments_has_user
  FOREIGN KEY (userId)
  REFERENCES test_db.users(id) 
  ON DELETE CASCADE,
  PRIMARY KEY (id)
);

ERROR 1215 (HY000): Cannot add foreign key constraint ERROR 1215(HY000):无法添加外键约束

This error is not so specific, and I can't really seem to pinpoint the error by reading other posts regarding similar error. 这个错误并不是那么具体,我似乎无法通过阅读有关类似错误的其他帖子来查明错误。

The datatypes need to be the same bigint is not the same as serial. 数据类型需要相同bigint与serial不同。 Try this 尝试这个

drop table if exists comments;
DROP TABLE IF EXISTS temp;

CREATE TABLE temp
(
  id bigint auto_increment, 
  username VARCHAR(20) NOT NULL,
  password VARCHAR(20) NOT NULL,
  PRIMARY KEY (id)
);

DROP TABLE IF EXISTS comments
;

CREATE TABLE comments
(
  id bigint auto_increment,
  content varchar(255) NOT NULL,
  userId bigint NOT NULL,
  CONSTRAINT fk_comments_has_user
  FOREIGN KEY (userId)
  REFERENCES temp(id) 
  ON DELETE CASCADE,
  PRIMARY KEY (id)
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM