我的数据库中有两个表,用户和帖子,我试图在post(author)和user(id)之间创建一个外键,但是我一直收到以下错误:
ERROR 1005 (HY000): Can't create table 'fortifya_rasp.#sql-c1c_2151546' (errno: 150)
我已经在SO和各种Google搜索上看到了其他几个问题,但没有一个回复解决了我的问题。这是我尝试过的查询
ALTER TABLE post ADD COLUMN author INT, ADD FOREIGN KEY (author) REFERENCES user(id);
以下是帖子的架构:
+-----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| timestamp | datetime | NO | | NULL | |
| title | varchar(255) | NO | | NULL | |
| content | longtext | NO | | NULL | |
+-----------+--------------+------+-----+---------+----------------+
用户:
+-------------------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------------------+--------------+------+-----+---------+-------+
| id | int(11) | NO | PRI | 0 | |
| firstname | varchar(255) | YES | | NULL | |
| lastname | varchar(255) | YES | | NULL | |
| fullname | varchar(255) | YES | | NULL | |
| email | varchar(255) | YES | | NULL | |
| password | varchar(100) | YES | | NULL | |
| joined_at | datetime | YES | | NULL | |
| is_admin | smallint(6) | YES | | NULL | |
+-------------------------+--------------+------+-----+---------+-------+
更新
我尝试过此查询后仍然收到同样的错误:
ALTER TABLE post ADD COLUMN author INT NOT NULL, ADD INDEX (author), ADD FOREIGN KEY (author) REFERENCES user(id);
当我在命令之后尝试获取状态时,我得到了:
ERROR 1227 (42000): Access denied; you need (at least one of) the PROCESS privilege(s) for this operation
然后我显然尝试添加权限以通过
查看此信息GRANT ALL PRIVILEGES ON * . * TO 'fortifya'@'%';
然后我得到一个与此相关的错误:
ERROR 1045 (28000): Access denied for user 'fortifya'@'localhost' (using password: YES)
当单独运行alter语句时,我可以添加author列并创建索引,如下所示,但在尝试创建外键时仍然失败:
+-----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| timestamp | datetime | NO | | NULL | |
| title | varchar(255) | NO | | NULL | |
| content | longtext | NO | | NULL | |
| author | int(11) | NO | | NULL | |
+-----------+--------------+------+-----+---------+----------------+
这可能是由与另一个表的外键关系引起的问题吗?
答案 0 :(得分:0)
作者列需要一个索引(并且必须是与用户(id)列完全相同的类型,即not null
)。
您可以将查询拆分为三个查询(添加列,添加索引,添加外键)或尝试在, add index(author)
之前直接添加, ADD FOREIGN KEY (author) REFERENCES user(id)
可以通过发出SHOW ENGINE INNDODB STATUS;