我有下表:
CREATE TABLE IF NOT EXISTS profile_claim_ruling_tasks (
profile_claim_ruling_task_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
account_id BIGINT UNSIGNED NOT NULL,
profile_id BIGINT UNSIGNED NOT NULL,
admin_task_status_id BIGINT UNSIGNED NOT NULL,
profile_claim_ruling_task_ref_id VARCHAR(36) NOT NULL,
profile_claim_ruling_task_requested_at DATETIME NOT NULL,
CONSTRAINT pk_profile_claim_ruling_tasks PRIMARY KEY (profile_claim_ruling_task_id),
CONSTRAINT fk_profile_claim_ruling_task_account_id FOREIGN KEY (account_id) REFERENCES accounts (account_id),
CONSTRAINT fk_profile_claim_ruling_task_profile_id FOREIGN KEY (profile_id) REFERENCES accounts (profile_id),
CONSTRAINT fk_profile_claim_ruling_task_admin_task_status_id FOREIGN KEY (admin_task_status_id) REFERENCES admin_task_statuses (admin_task_status_id),
INDEX idx_profile_claim_ruling_tasks_admin_task_status_id(admin_task_status_id),
CONSTRAINT uc_profile_claim_ruling_tasks_profile_claim_ruling_tasks_ref_id UNIQUE (profile_claim_ruling_task_ref_id)
);
当我在SELECT *
上执行accounts
时:
+------------+--------------------------------------+------------+
| account_id | account_ref_id | profile_id |
+------------+--------------------------------------+------------+
| 1 | 521ef2cb-01f9-49f3-a214-42e1514d7dc2 | 1 |
+------------+--------------------------------------+------------+
当我在SELECT *
上执行profiles
时:
+------------+--------------------------------------+
| profile_id | profile_ref_id |
+------------+--------------------------------------+
| 2 | 1d8caa66-e080-4cc6-88ff-a063e576bafa |
| 3 | 619a7ec6-813a-41f0-a1f9-16289893df5d |
| 4 | c50ceb2f-49f0-4319-b115-0a1454593c46 |
| 1 | d6369f9b-b66a-468c-86f9-a7e0abc75b65 |
+------------+--------------------------------------+
到目前为止,真好!但是当我运行以下插入时:
INSERT INTO profile_claim_ruling_tasks (
account_id,
profile_id,
admin_task_status_id,
profile_claim_ruling_task_ref_id,
profile_claim_ruling_task_requested_at
) VALUES (
1,
4,
1,
'4bed7334-e17b-462f-a7e6-454c3b2f5235',
'2018-01-29 13:12:57'
);
我收到以下错误:
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`myapp_db`.`profile_claim_ruling_tasks`, CONSTRAINT `fk_profile_claim_ruling_task_profile_id` FOREIGN KEY (`profile_id`) REFERENCES `accounts` (`profile_id`))
这里发生了什么?!
答案 0 :(得分:4)
FOREIGN KEY(
profile_id
)参考accounts
(profile_id
)
您正尝试在表profile_id=4
中插入profile_claim_ruling_tasks
的数据,表accounts (profile_id)
。
但是,profile_id=4
表中没有accounts
。您需要先填充accounts
表以解决此问题。
答案 1 :(得分:0)
您的第一个SHOW CREATE TABLE中似乎有一个错误,
CONSTRAINT fk_profile_claim_ruling_task_profile_id FOREIGN KEY(profile_id)参考帐户(profile_id),
应该是
CONSTRAINT fk_profile_claim_ruling_task_profile_id FOREIGN KEY(profile_id)参考个人资料(profile_id),
IMO。