php - 错误 1005 (HY000) : Can't create table 'db.POSTS' (errno: 150)

标签 php mysql foreign-keys innodb

您好,我在创建我的帖子数据库时遇到了问题。我正在尝试制作一个 forenge 键来链接到我的用户数据库。有人可以帮忙吗?

这是我的表格的代码:

CREATE TABLE USERS(

UserID int NOT NULL AUTO_INCREMENT,
UserName varchar(255),
UserPassword varchar(255) NOT NULL,
UserEmailAddress varchar(255) NOT NULL,
Admin int DEFAULT 0,
PRIMARY KEY (userID,UserName)
)ENGINE=InnoDB;

CREATE TABLE POSTS(

postID int NOT NULL AUTO_INCREMENT,
postTitle varchar(255) NOT NULL,
postContent varchar(255) NOT NULL,
category varchar(255) NOT NULL,
postDate Date NOT NULL,
postAuthor varchar(255),
tag varchar(255),

PRIMARY KEY(postID),
FOREIGN KEY(postAuthor) REFERENCES USERS(UserName)
)ENGINE=InnoDB;

这是最后一条 InnoDB 错误消息:

Error in foreign key constraint of table db/POSTS:
FOREIGN KEY(postAuthor) REFERENCES USERS(UserName)
)ENGINE=InnoDB:
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
for correct foreign key definition.

最佳答案

在第一个表上使用复合主键真的不应该是一个很好的理由。所以,我认为你打算:

CREATE TABLE USERS (
    UserID int NOT NULL AUTO_INCREMENT,
    UserName varchar(255),
    UserPassword varchar(255) NOT NULL,
    UserEmailAddress varchar(255) NOT NULL,
    Admin int DEFAULT 0,
    PRIMARY KEY (userID),
    UNIQUE (UserName)
);

CREATE TABLE POSTS (
    postID int NOT NULL AUTO_INCREMENT,
    postTitle varchar(255) NOT NULL,
    postContent varchar(255) NOT NULL,
    category varchar(255) NOT NULL,
    postDate Date NOT NULL,
    postAuthor int,
    tag varchar(255),

    PRIMARY KEY(postID),
    FOREIGN KEY(postAuthor) REFERENCES USERS(UserId)
);

一些注意事项:

  • 自动递增的 ID 在每一行都是唯一的。它是一个很好的主键。
  • 主键可以由多个列组成(称为复合主键)。但是,自动递增的 id 作为列之一没有多大意义。只需使用这样的 id 本身。
  • 如果您使用复合主键,则外键引用需要包括所有 列。
  • 我选择了 UserId 作为外键引用。您也可以使用 UserName(因为它是唯一的)。
  • UserName 对于外键来说是一个糟糕的选择,因为——可以想象——用户可以更改他或她的名字。

关于php - 错误 1005 (HY000) : Can't create table 'db.POSTS' (errno: 150),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36102595/

相关文章:

php - 如何在 CDbCriteria 中使用 Not Exists 子句进行查询?

php - 尽管使用 --tries,Laravel 队列不会自动失败

php - 如何从数组中删除键并更新索引?

mysql - 在 SQL 中更新记录但不覆盖....在开头添加文本

对于其中一个表,不同列上的 2 个表之间的 MySQL 多重内部连接

django - 如何防止 Django Admin 中 FK/MTM 字段的自(递归)选择

python - 使用 related_name 的 Django GenericForeignKey

PHP 有效的 http 状态

带有动态列的 MySQL 查询在没有内部联接的情况下无法正常工作

mysql - 如何使用insert和select语句在表中添加外键?