具有两个外键约束的表

时间:2019-06-30 18:53:21

标签: mysql mysql-8.0

当我试图制作一个包含2个外键的表时,我收到ERROR 1064(42000)。它说我的语法是错误的,但是我找不到任何错误。 我正在使用MySQL 8.0版

我只尝试了一个约束/没有第二个约束,它起作用了。但是他们两个我都出错了。

这有效:

CREATE TABLE IF NOT EXISTS Comment (
  id INT NOT NULL AUTO_INCREMENT,
  content VARCHAR(15) NOT NULL,
  date_posted DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  user_id INT NOT NULL,
  post_id INT NOT NULL,
  PRIMARY KEY (id),
  CONSTRAINT `fk_User_Comment`
    FOREIGN KEY (user_id)
    REFERENCES User (id)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION);

这不是:

CREATE TABLE IF NOT EXISTS Comment (
  id INT NOT NULL AUTO_INCREMENT,
  content VARCHAR(15) NOT NULL,
  date_posted DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  user_id INT NOT NULL,
  post_id INT NOT NULL,
  PRIMARY KEY (id),
  CONSTRAINT `fk_User_Comment`
    FOREIGN KEY (user_id)
    REFERENCES User (id)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION),
  CONSTRAINT `fk_Post_Comment`
    FOREIGN KEY (post_id)
    REFERENCES Post (id)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION);

1 个答案:

答案 0 :(得分:0)

是的,我多了一个括号。 谢谢你们。

CREATE TABLE IF NOT EXISTS Comment (
  id INT NOT NULL AUTO_INCREMENT,
  content VARCHAR(15) NOT NULL,
  date_posted DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  user_id INT NOT NULL,
  post_id INT NOT NULL,
  PRIMARY KEY (id),
  CONSTRAINT `fk_User_Comment`
    FOREIGN KEY (user_id)
    REFERENCES User (id)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Post_Comment`
    FOREIGN KEY (post_id)
    REFERENCES Post (id)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION);