将外键添加到现有表

时间:2018-10-30 14:49:52

标签: mysql

我有一个父orders表,如下所示:

+---------------+---------------+------+-----+-----------+----------------+
| Field         | Type          | Null | Key | Default   | Extra          |
+---------------+---------------+------+-----+-----------+----------------+
| id            | int(11)       | NO   | PRI | NULL      | auto_increment |
| pnref         | varchar(50)   | YES  | UNI | NULL      |                |
| customerid    | int(11)       | YES  |     | NULL      |                |
+-------------------------------------------------------------------------+

我有一个子orders_content表,如下所示:

+------------------+--------------+------+-----+---------+----------------+
| Field            | Type         | Null | Key | Default | Extra          |
+------------------+--------------+------+-----+---------+----------------+
| id               | int(6)       | NO   | PRI | NULL    | auto_increment |
| orderid          | int(11)      | NO   |     | NULL    |                |
| status           | varchar(50)  | YES  |     | pending |                |
+------------------+--------------+------+-----+---------+----------------+

我正在尝试像这样添加FOREIGN KEY

ALTER TABLE orders_content 
ADD CONSTRAINT fk_orders_content 
FOREIGN KEY(orderid) REFERENCES orders(id)
ON DELETE CASCADE ON UPDATE CASCADE;

我无法解决失败的原因:

1452 - Cannot add or update a child row: a foreign key constraint fails ( gls .#sql-1744_4d58 , CONSTRAINT fk_orders_content FOREIGN KEY ( orderid ) REFERENCES订单( id ) ON DELETE CASCADE ON UPDATE CASCADE)

如果任何人都可以看到我的一个或多个错误,我将不胜感激。

0 个答案:

没有答案