我在使用我的外键与我的一些主键匹配时遇到了一些麻烦。我一直收到错误"Error: Cannot add foreign key constraint"
。我不知道自己做错了什么,但可能是因为我已经盯着它看了太久。有什么建议吗?
//customer table
statement.execute("CREATE TABLE IF NOT EXISTS mydb.Customers ("
+ " FirstName VARCHAR(21) NOT NULL, "
+ " StreetAddress VARCHAR(45) NULL, "
+ " TelephoneNumber VARCHAR(45) NULL, "
+ " SetOfFrequentFlyerMemberships VARCHAR(45) NULL, "
+ " PreferredPaymentMethod VARCHAR(45) NULL, "
+ " Preferences VARCHAR(45) NULL, "
+ " City VARCHAR(45) NULL, "
+ " State INT NULL, "
+ " LastName VARCHAR(45) NULL, "
+ " CustomerID VARCHAR(45) NOT NULL, "
+ " Customerscol VARCHAR(45) NOT NULL, "
+ " PRIMARY KEY (CustomerID, Preferences))");
//reservation table
statement.execute("CREATE TABLE IF NOT EXISTS mydb.Reservations ( "
+ " CustomerID INT NOT NULL, "
+ " TravelAgent VARCHAR(45) NOT NULL, "
+ " FlightID INT NULL, "
+ " PaymentType VARCHAR(45) NULL, "
+ " StatusOfReservation VARCHAR(45) NULL, "
+ " ReservationID VARCHAR(45) NOT NULL, "
+ " PaymentID INT NOT NULL, "
+ " Preferences VARCHAR(45) NULL, "
+ " PRIMARY KEY (ReservationID), "
+ " CONSTRAINT fk_Reservations_Customers1 "
+ " FOREIGN KEY (CustomerID) "
+ " REFERENCES mydb.Customers(CustomerID), "
+ " CONSTRAINT fk_Reservations_Payment1 "
+ " FOREIGN KEY (PaymentID) "
+ " REFERENCES mydb.Payment(PaymentID), "
+ " CONSTRAINT fk_Reservations_Flights1 "
+ " FOREIGN KEY (FlightID) "
+ " REFERENCES mydb.Flights(FlightID), "
+ " CONSTRAINT fk_Reservations_Preference1 "
+ " FOREIGN KEY (Preferences) "
+ " REFERENCES mydb.Customers(Preferences))");
//frequent flyer membership
statement.execute("CREATE TABLE IF NOT EXISTS mydb.FrequentFlyerMemberships ( "
+ " FrequentFlyerID INT NOT NULL, "
+ " customerID VARCHAR(45) NULL, "
+ " ReservationID VARCHAR(45) NULL, "
+ " PRIMARY KEY (FrequentFlyerID), "
+ " CONSTRAINT fk_FrequentFlyerMemberships_Reservations1 "
+ " FOREIGN KEY (ReservationID) "
+ " REFERENCES mydb.Reservations(ReservationID))");
这不是我的所有代码,但这些是我似乎遇到问题的唯一块。
答案 0 :(得分:3)
使用类似下面的脚本为其他表的组合键创建外键 这将有效
CONSTRAINT fk_Reservations_Customers1
FOREIGN KEY (CustomerID,Preferences)
REFERENCES stackoverflowprob.Customers(CustomerID,Preferences));