[英]Two columns in same table and same foreign key
I'm developing an application, actually a billing system. 我正在开发一个应用程序,实际上是一个计费系统。 Here accountant can add invoice for a client.
在这里,会计可以为客户添加发票。
I have two tables, users
and invoices
: 我有两个表,
users
和invoices
:
invoices (user_id, created_by)
users (id)
Invoices has two columns, user_id
and created_by
, I want both to be linked with id
of the users
table. 发票有两列,
user_id
和created_by
,我希望两者都与users
表的id
链接。
Already user_id
has been added as foreign key. 已经将
user_id
添加为外键。 Now I'm trying to add created_by
as foreign key. 现在,我试图将
created_by
添加为外键。 So issued following command: 因此发出以下命令:
ALTER TABLE `invoices`
ADD FOREIGN KEY (`created_by`) REFERENCES `secureap_maind`.`users` (`id`)
ON DELETE RESTRICT ON UPDATE RESTRICT;
And I'm getting an error message. 而且我收到一条错误消息。
#1452 - Cannot add or update a child row: a foreign key constraint fails (
secureap_maind
.#sql-3717_a323d
, CONSTRAINT#sql-3717_a323d_ibfk_2
FOREIGN KEY (created_by
) REFERENCESusers
(id
))#
secureap_maind
无法添加或更新子行:外键约束失败(secureap_maind
。#sql-3717_a323d
,CONSTRAINT#sql-3717_a323d_ibfk_2
FOREIGN KEY(created_by
)参考users
(id
))
I'm not sure if I can add two columns as foreign key. 我不确定是否可以添加两列作为外键。 IF possible, can you please advice to do that?
如果可能的话,您能建议这样做吗?
Thanks in advance. 提前致谢。
This SO post implies that removing your ON DELETE RESTRICT
clause from the ALTER TABLE
statement might solve your problem. 这篇SO帖子暗示从
ALTER TABLE
语句中删除ON DELETE RESTRICT
子句可能会解决您的问题。 Try running this query instead: 尝试改为运行以下查询:
ALTER TABLE `invoices`
ADD FOREIGN KEY (`created_by`) REFERENCES `secureap_maind`.`users`(`id`)
I am assuming that the invoices
table was created using InnoDB rather than MyISAM, the latter which does not enforce foreign keys. 我假设
invoices
表是使用InnoDB而不是MyISAM创建的,后者不强制执行外键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.