简体   繁体   English

添加外键错误

[英]Adding Foreign Key Error

I want to add a foreign key from Table Customers , row= "Customer ID" to Table Pet, row= "Customer ID" . 我想从Table Customers row= "Customer ID"的外键添加到Table Pet的row= "Customer ID"

-- Table structure for table `Customers`

CREATE TABLE IF NOT EXISTS `Customers` (
  `CustomerID` varchar(50) NOT NULL,
  `Fname` varchar(50) DEFAULT NULL,
  `LName` varchar(20) DEFAULT NULL,
  `Tel` varchar(20) DEFAULT NULL,
  `Fax` varchar(20) DEFAULT NULL,
  `CustType` varchar(20) DEFAULT NULL,
  `AdState` varchar(50) DEFAULT NULL,
  `City` varchar(20) DEFAULT NULL,
  `Zip` varchar(20) DEFAULT NULL,
  `Street` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`CustomerID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- Dumping data for table `Customers`

INSERT INTO `Customers` (`CustomerID`, `Fname`, `LName`, `Tel`, `Fax`, `CustType`, `AdState`, `City`, `Zip`, `Street`) VALUES
('AC001', 'All', 'Creatures', '206 555-6622', '206 555-7854', '2', 'WA', 'Tall Pines', '98746', '21 Grace St.'),
('AD001', 'Johnathan', 'Adams', '206 555 7623', '206 555 8855', '1', 'WA', 'Mountain View', '984101012', '66 10th St'),
('AD002', 'William', 'Adams', '503 555 7623', '503 555 7319', '1', 'OR', 'Lakewille', '9740110011', '1122 10th_St'),
('AK001', 'Animal', 'Kingdom', '208 555 7108', '', '2', 'ID', 'Borderville', '834835646', '15 Marlin Lane');

CREATE TABLE IF NOT EXISTS `Pet` (
  `ID` varchar(50) NOT NULL,
  `CustomerID` varchar(50) NOT NULL,
  `Gender` varchar(20) DEFAULT NULL,
  `Race` varchar(20) DEFAULT NULL,
  `Name` varchar(20) DEFAULT NULL,
  `Kind` varchar(20) DEFAULT NULL,
  `Birthday` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- Dumping data for table `Pet`

INSERT INTO `Pet` (`ID`, `CustomerID`, `Gender`, `Race`, `Name`, `Kind`, `Birthday`) VALUES
('AC001-01', '0', 'M', 'Long Ear', 'Bobo', 'Rabbit', '4/8/92'),
('AC001-02', '0', 'F', 'Chameleon', 'Presto Chango', 'Lizard', '5/1/92'),
('AC001-03', '0', 'M', '', 'Stinky', 'Skunk', '8/1/91'),
('AC001-04', '0', 'M', 'German Shepherd', 'Fido', 'Dog', '6/1/90'),
('AD001-01', '0', 'F', 'Potbelly', 'Patty', 'Pig', '2/15/91'),
('AD001-02', '0', 'M', 'Palomino', 'Rising Sun', 'Horse', '4/10/90'),
('AD002-01', '0', 'F', 'Mixed', 'Dee Dee', 'Dog', '2/15/91'),
('AK001-03', '0', 'M', '', 'Jerry', 'Rat', '2/1/88'),
('AK001-07', '0', 'M', 'Beagle', 'Luigi', 'Dog', '8/1/92');

This is the code that I have been using to add the foreign key: 这是我用来添加外键的代码:

ALTER TABLE Pet ADD CONSTRAINT Pet_FK 
FOREIGN KEY (CustomerID) REFERENCES Customers (CustomerID);

And the error message from this is: 而从此错误消息是:

#1452 - Cannot add or update a child row: a foreign key constraint fails     
(`hospital`.`#sql-523_76e`, CONSTRAINT `Pet_FK` FOREIGN KEY (`CustomerID`) 
REFERENCES `Customers` (`CustomerID`))

I am quite a beginner with database and I have no idea what I should try next. 我是数据库的初学者,我不知道下一步该怎么做。

I think that's all. 我认为就这些。 Im still new to this stackoverflow so if I missed any necessary information please tell me and I will add it. 我对这个stackoverflow还是陌生的,所以如果我错过了任何必要的信息,请告诉我,我将添加它。

UPDATE*** UPDATE ***

ALTER TABLE Customers ADD CONSTRAINT Customers_FK 
FOREIGN KEY (CustomerID) REFERENCES Pet (CustomerID);

I swapped some positions and the error code I recieve is: 我调换了一些职位,收到的错误代码是:

#1215 - Cannot add foreign key constraint

Simple one. 简单的一个。

There is an row that contains the CustomerID that can't be matched. 有一行包含无法匹配的客户ID。 So first you need to remove/edit/handle the entry and than add a foreign key. 因此,首先您需要删除/编辑/处理条目,然后添加外键。

The CustomerID you're trying to enter in PETS table, does not exist in CUSTOMERS table, and that is why your Foreign Key constraint fails and throws error. 您尝试在PETS表中输入的CustomerIDCUSTOMERS表中不存在,这就是为什么外键约束失败并引发错误的原因。

You need to ensure that the CustomerIDs you're entering in your Pets table, exist in Customers table OR simply insert NULL in the PETS.CUSTOMERID field 您需要确保在Pets表中输入的CustomerID,在Customers表中存在,或者仅在PETS.CUSTOMERID字段中插入NULL

Enterx is right. Enterx是正确的。

For being able to detect not matching row : 为了能够检测到不匹配的行:

SELECT * FROM Pet p WHERE (SELECT COUNT(*) FROM Customers c WHERE c.CustomerID=p.CustomerID)=0

Just change SELECT * by DELETE for deleting missmatching Pet entry. 只需将SELECT *更改为DELETE即可删除不匹配的Pet条目。 You can UPDATE Pet.CustomerID to NULL too. 您也可以将Pet.CustomerID更新为NULL。 But you have to define CustomerID, from Pet table, with NULL option (and not NOT NULL) 但是您必须在Pet表中使用NULL选项(而不是NOT NULL)定义CustomerID。

try this 尝试这个

CREATE TABLE IF NOT EXISTS `Pet` (
  `ID` varchar(50) NOT NULL,
  FOREIGN KEY (`CustomerID`) REFERENCES Customers(CustomerID) varchar(50) NOT NULL,
  `Gender` varchar(20) DEFAULT NULL,
  `Race` varchar(20) DEFAULT NULL,
  `Name` varchar(20) DEFAULT NULL,
  `Kind` varchar(20) DEFAULT NULL,
  `Birthday` varchar(20) DEFAULT NULL,
   PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

It looks like to me that you inserted values in table Pet's column ID when they should have been inserted in CustomerID and vice-versa. 在我看来,您应该将表Pet的列ID值插入到CustomerID ,反之亦然。

By the way, it's not really good to have IDs as VARCHARs, specially when they are foreign keys. 顺便说一句,将ID作为VARCHAR并不是很好,特别是当它们是外键时。 This makes queries processing slower, although your tables don't look like they'll have a huge number of rows for this to make a difference. 这会使查询处理变慢,尽管您的表看起来并没有太多的行,这可以有所作为。 Anyway, it's just an observation. 无论如何,这只是一个观察。 I would consider have artificial int primary keys in my tables. 我会考虑在表中使用人工int主键。

EDIT 编辑

I had misread table Pet's values. 我误读了表Pet的值。 The other answers here are right. 这里的其他答案是正确的。 You need to update those 0 values in CustomerID column to match existing CustomerIDs in Customer table or delete them, otherwise you'll get an error when trying to create the FK. 您需要更新“客户ID”列中的那些0值以匹配“客户”表中现有的客户ID或将其删除,否则尝试创建FK时会收到错误消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM