how to reference multiple fks from different tables in MySQL - mysql

i have been looking around and i cannot find the correct way to do this in sql the current way i have coded it just causes my third table to fail but the rest of the code worked great up until the third table, i just need the third table to include fks from both the previous tables
first table
SET FOREIGN_KEY_CHECKS = 0;
DROP TABLE IF EXISTS Customer;
CREATE TABLE Customer
(
CustomerNumber int NOT NULL,
CustomerName varchar(255),
CustomerAddress varchar(255),
CustomerPhoneNumber varchar(255),
JoinDate varchar(255),
PetName varchar(255),
PayScheme varchar(255),
PremiumPayDate varchar(255),
PRIMARY KEY (CustomerNumber, PetName)
);
second table
DROP TABLE IF EXISTS Policies;
CREATE TABLE Policies
(
PolicyID int NOT NULL,
PolicyNumber int NOT NULL,
PetType varchar(255),
CustomerNumber int NOT NULL,
PetName varchar(255),
EffectiveDate varchar(255),
PRIMARY KEY (PolicyID),
CONSTRAINT fk_CustomerNumber_PetName
FOREIGN KEY (CustomerNumber, PetName)
REFERENCES Customer(CustomerNumber, PetName)
);
third table
DROP TABLE IF EXISTS Claims;
CREATE TABLE Claims
(
ClaimsID int NOT NULL,
AmountForReimbursement varchar(255),
PolicyID int NOT NULL,
PetName varchar(255),
PRIMARY KEY (ClaimsID),
CONSTRAINT fk_PolicyID_PetName
FOREIGN KEY (PolicyID, PetName)
REFERENCES Policies(PolicyID), Customer(PetName)
);

You should consider going through MySQL documentation. You have got the table creation wrong again for Claims. It should be like below
CREATE TABLE Claims
(
ClaimsID int NOT NULL,
AmountForReimbursement varchar(255),
PolicyID int NOT NULL,
PetName varchar(255),
CustomerNumber int NOT NULL,
PRIMARY KEY (ClaimsID),
CONSTRAINT fk_PolicyID_PetName
FOREIGN KEY (PolicyID) REFERENCES Policies(PolicyID),
FOREIGN KEY (CustomerNumber, PetName) REFERENCES Customer(CustomerNumber, PetName)
);
It's always recommended and you should actually refer both the PK column since you have a composite PK defined

Related

How to set up Foreign keys MySQL

I am very new to SQL, I am using MySQL running a server set up for me to complete an assignment.
I can't understand what I am doing wrong here when assigning the foreign keys, here is my code
CREATE TABLE Customers (
CustomersID int NOT NULL AUTO_INCREMENT,
CustomerName varchar(50),
AddressLine1 varchar(50),
AddressLine2 varchar(50),
City varchar(50),
State varchar(50),
PostalCode varchar(50),
YTDPurchases decimal(19,2),
PRIMARY KEY (CustomersID)
);
CREATE TABLE TermsCode (
TermsCodeID varchar(50) NOT NULL,
Description varchar(50)
);
CREATE TABLE Invoices (
InvoiceID int NOT NULL AUTO_INCREMENT,
CustomerID int,
InvoiceDate datetime,
TermsCodeID varchar(50),
TotalDue decimal(19,2),
PRIMARY KEY (InvoiceID),
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomersID),
FOREIGN KEY (TermsCodeID) REFERENCES TermsCode(TermsCodeID)
);
I get this error
MySQL said: Documentation
#1005 - Can't create table table.Invoices` (errno: 150 "Foreign key constraint is incorrectly formed")
You need to add a primary key to the second table, as in:
CREATE TABLE TermsCode (
TermsCodeID varchar(50) NOT NULL,
Description varchar(50),
primary key(TermsCodeID)
);
Once you do that, the tables' creation works well. See example at db<>fiddle.

mysql error 1064 when creating table. What can I check for?

I'm getting an ERROR 1064 (42000) at line 21, which is VIN_Number in Vehicle table. Entity Inventory gets built without a problem, VIN_Number is of type varchar(17) for all occurrences. I believe the tables are being built in the correct order. I can't find any spelling or punctuation errors. I'm out of ideas of things I should checked. What is it that I'm missing?
Note: I getting an error for Invoice as well, but I know that it can't be created until Vehicle gets created.
ALTER TABLE Vehicle DROP FOREIGN KEY fk_Veh_Vehicle_TypeID;
ALTER TABLE Inventory DROP FOREIGN KEY fk_Inv_Vehicle_TypeID;
ALTER TABLE Invoice DROP FOREIGN KEY fk_Customer_ID;
ALTER TABLE Invoice DROP FOREIGN KEY fk_Sales_Person_ID;
ALTER TABLE Invoice DROP FOREIGN KEY fk_VIN_Number;
DROP TABLE IF EXISTS Vehicle, VehicleType,
Invoice, Customer, SalesPerson, Inventory;
CREATE TABLE VehicleType (
Vehicle_TypeID int NOT NULL,
Veh_Make varchar(15),
Veh_Model varchar(15),
Veh_Year int,
PRIMARY KEY (Vehicle_TypeID)
) Engine=InnoDB;
CREATE TABLE Vehicle (
VIN_Number varchar(17) NOT NULL,
Vehicle_TypeID int NOT NULL,
Condition varchar(10),
Color varchar(8),
PRIMARY KEY (VIN_Number),
CONSTRAINT fk_Veh_Vehicle_TypeID FOREIGN KEY(Vehicle_TypeID)
REFERENCES VehicleType(Vehicle_TypeID)
) Engine=InnoDB;
CREATE TABLE Inventory (
Stock_ID int NOT NULL,
Vehicle_TypeID int NOT NULL,
Quantity int,
PRIMARY KEY (Stock_ID),
CONSTRAINT fk_Inv_Vehicle_TypeID FOREIGN KEY (Vehicle_TypeID)
REFERENCES VehicleType(Vehicle_TypeID)
) Engine=InnoDB;
CREATE TABLE Customer (
Customer_ID varchar(10) NOT NULL,
Cus_LastName varchar(15),
Cus_FirstName varchar(15),
Cus_Street varchar(20),
Cus_City varchar(15),
Cus_Zip varchar(5),
Cus_Phone varchar(10),
PRIMARY KEY (Customer_ID)
) Engine=InnoDB;
CREATE TABLE SalesPerson (
Sales_Person_ID varchar(10) NOT NULL,
Sal_LastName varchar(15),
Sal_FirstName varchar(15),
Sal_Street varchar(15),
Sal_City varchar(15),
Sal_Zip varchar(5),
Sal_Phone varchar(10),
Sal_Years_Worked int,
Sal_Commission_Rate float(4),
PRIMARY KEY (Sales_Person_ID)
) Engine=InnoDB;
CREATE TABLE Invoice (
Invoice_ID varchar(10) NOT NULL,
Customer_ID varchar(10) NOT NULL,
Sales_Person_ID varchar(10) NOT NULL,
VIN_Number varchar(17) NOT NULL,
Price float(10),
PRIMARY KEY (Invoice_ID),
CONSTRAINT fk_Customer_ID FOREIGN KEY (Customer_ID)
REFERENCES Customer(Customer_ID),
CONSTRAINT fk_Sales_Person_ID FOREIGN KEY (Sales_Person_ID)
REFERENCES SalesPerson(Sales_Person_ID),
CONSTRAINT fk_VIN_Number FOREIGN KEY (VIN_Number)
REFERENCES Vehicle(VIN_Number)
) Engine=InnoDB;
In the definition of the Vehicle table you have a column named condition which is a reserved keyword in MySQL (reference). Either use another name for the column or enclose it in backticks like this: `condition`
Using keywords (reserved or not) for object names is generally something you want to avoid.

MySQL Error 1217 [duplicate]

This question already has an answer here:
MySQL Error 1005?
(1 answer)
Closed 7 years ago.
I'm getting this error, and I know it's coming from the DROP TABLE IF statements, but I don't know how else to organize the drops for it to work. I've tried rearranging them but it won't work. The problem came when I introduced the Passenger table but I don't know how to fix it.
DROP TABLE IF EXISTS `Passenger`;
DROP TABLE IF EXISTS `ProductInvoice`;
DROP TABLE IF EXISTS `Invoice`;
DROP TABLE IF EXISTS `Product`;
DROP TABLE IF EXISTS `Customer`;
DROP TABLE IF EXISTS `Person`;
DROP TABLE IF EXISTS `Airport`;
DROP TABLE IF EXISTS `Address`;
DROP TABLE IF EXISTS `Email`;
CREATE TABLE Address
(
AddressID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(AddressID),
AddressStreet VARCHAR(255),
AddressCity VARCHAR(255),
AddressState VARCHAR(255),
AddressZip VARCHAR(255),
AddressCountry VARCHAR(255)
);
CREATE TABLE Email
(
EmailID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(EmailID),
EmailAddress VARCHAR(255)
);
CREATE TABLE Person
(
PersonID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(PersonID),
PersonCode VARCHAR(255),
PersonLastName VARCHAR(255),
PersonFirstName VARCHAR(255),
AddressID INT NOT NULL,
FOREIGN KEY `fk_Person_to_Address` (AddressID) REFERENCES Address(AddressID),
PersonPhone VARCHAR(255),
EmailID INT NOT NULL,
FOREIGN KEY `fk_Person_to_Email` (EmailID) REFERENCES Email(EmailID)
);
CREATE TABLE Airport
(
AirportID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(AirportID),
AirportCode VARCHAR(255),
AirportName VARCHAR(255),
AddressID INT NOT NULL,
FOREIGN KEY `fk_Airport_to_Address` (AddressID) REFERENCES Address(AddressID),
AirportLatDeg INT NOT NULL,
AirportLatMin INT NOT NULL,
AirportLongDeg INT NOT NULL,
AirportLongMin INT NOT NULL,
AirportPassFacilityFee FLOAT NOT NULL
);
CREATE TABLE Customer
(
CustomerID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(CustomerID),
CustomerCode VARCHAR(255),
CustomerType VARCHAR(255),
PrimaryContact INT NOT NULL,
FOREIGN KEY `fk_Customer_to_Person` (PrimaryContact) REFERENCES Person(PersonID),
CustomerName VARCHAR(255),
CustomerAirlineMiles FLOAT NOT NULL
);
CREATE TABLE Product
(
ProductID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(ProductID),
ProductCode VARCHAR(255),
ProductType VARCHAR(255),
DepAirportCode INT,
FOREIGN KEY `fk_Product_to_Airport` (DepAirportCode) REFERENCES Airport(AirportID),
ArrAirportCode INT,
FOREIGN KEY `frk_Product_to_Airport` (ArrAirportCode) REFERENCES Airport(AirportID),
DepartureTime VARCHAR(255),
ArrivalTime VARCHAR(255),
FlightNumber VARCHAR(255),
FlightClass VARCHAR(255),
AircraftType VARCHAR(255),
SeasonStartDate VARCHAR(255),
SeasonEndDate VARCHAR(255),
OffseasonRebate FLOAT,
AwardPointsPerMile FLOAT,
BaggageTicketCode INT,
FOREIGN KEY `fk_Product_to_Product` (BaggageTicketCode) REFERENCES Product(ProductID),
InsuranceName VARCHAR(255),
SpecialTypeOfService VARCHAR(255),
RefreshmentName VARCHAR(255),
RefreshmentCost FLOAT
);
CREATE TABLE Invoice
(
InvoiceID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(InvoiceID),
InvoiceCode VARCHAR(255),
CustomerCode INT NOT NULL,
FOREIGN KEY `fk_Invoice_to_Customer` (CustomerCode) REFERENCES Customer(CustomerID),
SalespersonCode INT NOT NULL,
FOREIGN KEY `fk_Invoice_to_Person` (SalespersonCode) REFERENCES Person(PersonID),
InvoiceDate VARCHAR(255)
);
CREATE TABLE ProductInvoice
(
ProductInvoiceID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(ProductInvoiceID),
ProductID INT NOT NULL,
FOREIGN KEY `fk_ProductInvoice_to_Product` (ProductID) REFERENCES Product(ProductID),
InvoiceID INT NOT NULL,
FOREIGN KEY `fk_ProductInvoice_to_Invoice`(InvoiceID) REFERENCES Invoice(InvoiceID),
TravelDate VARCHAR(255),
NumOfPassengers INT NOT NULL,
Seat VARCHAR(255),
TicketNote VARCHAR(255)
);
CREATE TABLE Passenger
(
PassengerID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(PassengerID),
PersonID INT NOT NULL,
FOREIGN KEY `fk_Passenger_to_Person` (PersonID) REFERENCES Person(PersonID),
IdentityNumber VARCHAR(255),
PassengerAge INT NOT NULL,
PassengerNationality VARCHAR(255),
ProductInvoiceID INT NOT NULL,
FOREIGN KEY `fk_Passenger_to_ProductInvoice` (ProductInvoiceID)
REFERENCES ProductInvoice(ProductInvoiceID)
);
This is the error I get:
Error Code: 1217. Cannot delete or update a parent row: a foreign key constraint fails
and it fails on the DROP TABLE for Invoice.
Disable foreign key checks or.
Drop the whole database or.
Run the script twice or.
Drop the fk constraints first.
Mysql workbench will generate a script for you if you highlight all if the tables and create a drop script. Same with the mysql dump utility.
How to temporarily disable a foreign key constraint in MySQL?

query on mysql table creation composite primary key from foreign keys of two tables

I have the following tables
books(
bkid varchar(255),
bkname varchar(255),
bkauth varchar(255),
bkpub varchar(255),
bkedn int(10)
)
members(
memid varchar(255),
memname varchar(255),
memaddr varchar(255),
memcon varchar(255),
mememail varchar(255)
)
bkid and memid are primary keys.
Now I am trying to make a composite primary key (bkid and memid) taking them as foreign keys from the tables books and members, the syntax is giving me some errors and I am not able to create the new table.
create table issuebooks(
bkid varchar(255),
memid varchar(255),
issuestatus varchar(255),
references foreign key bkid(books),
references foreign key memid(members),
primary key (bkid,memid)
);
Your create table statement is incorrect. This will work (tested on SQLFiddle)
create table issuebooks(
bkid varchar(255) references bkid(books),
memid varchar(255) references memid(members),
issuestatus varchar(255),
primary key (bkid,memid)
);
Advice... use integer id columns instead of VARCHAR(255) if you can... you won't regret it. And make those columns NOT NULL.

Adding composite foreign key fails in MySQL5

I am trying to enforce that the state/province and country names in the address information for users comes from a set of tables where I list countries and state/provinces. In order to do this I tried running an alter table command like this...
ALTER TABLE User
ADD FOREIGN KEY (stateProvince,country)
REFERENCES `StateProvince`(`name`,`countryName`);
Then I get this message...
Create table 'realtorprint_dev/#sql-d5c_3d' with foreign key
constraint failed. There is no index in the referenced table where the
referenced columns appear as the first columns.
Does anybody have an idea how to handle this error message?
Here is the create for the state and country tables...
CREATE TABLE Country (
name varchar(40) NOT NULL,
abbreviation varchar(4) NOT NULL,
PRIMARY KEY (name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE StateProvince (
countryName varchar(40) NOT NULL,
name varchar(100) NOT NULL,
abbreviation varchar(3) NOT NULL,
PRIMARY KEY (countryName,name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
alter table StateProvince
add constraint FK_StateProvince_Country
foreign key (countryName)
references Country (name);
And now for the user table...
create table realtorprint_dev.user (
id bigint not null,
created datetime,
email varchar(255) not null,
fax varchar(255),
mobile varchar(255),
name varchar(255),
password varchar(255),
phone varchar(255),
title varchar(255),
tollFree varchar(255),
updated datetime,
web varchar(255),
brokerage_id bigint,
address varchar(255),
city varchar(255),
country varchar(255),
stateProvince varchar(255),
type varchar(255),
zipPostal varchar(255),
activated bit not null,
locked bit not null,
primary key (id),
foreign key FK285FEB6722226 (brokerage_id) references brokerage(id)
);
There is no index in the referenced table where the referenced columns appear as the first columns.
You need an index on StateProvince.(name,countryName), but you have an index on StateProvince.(countryName,name). Try reversing the order of your index, or of your FK reference.
Since you didn't show the create statement i'm not sure, but I beleve this has to do with the realtorprint_dev table not having a primairy key.