2

我有两个名为“customers”的表,以“productid”作为主键

 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

和具有“单位”作为主键的“产品”

 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

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

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

但上面的代码结束说明

错误 1452 (23000):无法添加或更新子行:外键约束失败 ( products. #sql-6e0_2, CONSTRAINT ckFOREIGN KEY ( ProductID) REFEREN CES customers( ProductID))"

4

1 回答 1

2

您正在将密钥添加到错误的表中。你想制作customers.ProductID一个外键products.ProductID

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

它失败的原因是因为您的 IDproduct.ProductID不存在,customers.ProductID因此约束失败。

于 2013-10-03T05:49:58.057 回答