无法在MySQL中添加外键

时间:2013-10-03 05:44:41

标签: mysql

我有两个表将'productid'作为主键命名为'customers'

 CustomerID | CustomerName | ContactName | Address  | PostalCode | Country | ProductID
------------+--------------+-------------+----------+------------+---------+-----------
          1 | John         | Jones       | Payson   | 34213      | Germany |         2
          2 | Mary         | Edward      | Sandiego | 43561      | Mexico  |        34
          3 | Eric         | Howell      | Phoenix  | 50023      | Mexico  |        11
          4 | Gus          | Gray        | Tucson   | 50021      | USA     |        54
          5 | Erica        | Williams    | Payson   | 76983      | UK      |        67
          6 | Elroy        | Cleaver     | Baghdad  | 34721      | France  |        55

和'产品'将'unit'作为主键

 ProductID | ProductName   | SupplierID | CategoryID | Unit              |Price| Date
-----------+---------------------------+------------+------------+----------------------+--
         1 | Chais         |          1 |          1 | 10 boxesx20 bags  | 18  | 2008-11-11
         2 | Chang         |          1 |          1 | 24-12 oz bottles  | 19  | 2008-11-09
         3 | Aniseed Syrup |          1 |          2 | 12-550 ml bottles | 10  | 2008-05-12
        15 | Genen Shouyu  |          6 |          2 | 24-250 ml bottles | 15  | 2008-06-23
        16 | Pavlova       |          7 |          3 | 32-500 g boxes    | 17  | 2007-12-30
        21 | Sir Rodney's  |          8 |          3 | 24 pkgs.x4 pieces | 10  | 2007-01-09
        25 | NuNuCa Nuß    |         11 |          3 | 20 - 450 g glasses| 14  | 2007-05-04
        36 | Inlagd Sill   |         17 |         18 | 24 - 250 g jars   | 19  | 2007-02-09

使用以下代码将产品表中的productid作为外键

alter table products add constraint ck foreign key(productid) references customers(productid);

但上面的代码结尾说明

  

错误1452(23000):无法添加或更新子行:外键约束失败(products#sql-6e0_2,CONSTRAINT ck FOREIGN KEY(ProductID)参照的文   CES customersProductID))“

1 个答案:

答案 0 :(得分:2)

您正在将密钥添加到错误的表中。您希望customers.ProductID成为products.ProductID

的外键
ALTER TABLE `customers`
ADD CONSTRAINT `ck`
FOREIGN KEY(`ProductID`) REFERENCES `products` (`ProcuctID`)

失败的原因是因为product.ProductID中的customers.ProductID中存在{{1}}中的ID,因此约束失败。