Can't create tables in Mysql - mysql

I have these tables but only managed to create
Insurance_Policy_Type
Historical_Era
Region
Reference
Organisation
Geographic_Area
The rest of them are giving me errors such as,
"Cant create table" on Loan_Item,
"Reference_Id dont exist" on Historical_Era_Reference
"error 1064 (4200)" on Loan
CREATE TABLE Insurance_Policy_Type (
Insurance_Policy_Type_Id INT (4),
Insurance_Policy_Type_Name VARCHAR (30),
PRIMARY KEY (Insurance_Policy_Type_Id));
CREATE TABLE Historical_Era (
Historical_Era_Id INT (4),
Historical_Era_Name VARCHAR (30),
PRIMARY KEY (Historical_Era_Id));
CREATE TABLE Reference (
Reference_Id INT (4),
Reference_Name VARCHAR (30),
Author VARCHAR (30),
PRIMARY KEY (Reference_Id));
CREATE TABLE Region (
Region_Id INT (4),
Region_Name VARCHAR (30),
PRIMARY KEY (Region_Id));
CREATE TABLE Organisation (
Organisation_Id INT (4),
Organisation_Name VARCHAR (30),
PRIMARY KEY (Organisation_Id));
CREATE TABLE Items (
Item_Id INT (4),
Item_Name VARCHAR (30),
Description VARCHAR (30),
Insurance_Policy_Type_Id INT (4),
Geo_Area_Id INT (4)
PRIMARY KEY (Item_Id),
FOREIGN KEY (Insurance_Policy_Type_Id) REFERENCES Insurance_Policy_Type(Insurance_Policy_Type_Id),
FOREIGN KEY (Geo_Area_Id) REFERENCES Geographic_Area(Geo_Area_Id));
CREATE TABLE GeoArea_HistEra (
Geo_Area_Id INT (4),
Historical_Era_Id INT (4),
FOREIGN KEY (Geo_Area_Id) REFERENCES Geographical_Area(Geo_Area_Id)),
FOREIGN KEY (Historical_Era_Id) REFERENCES Historical_Era(Historical_Era_Id));
CREATE TABLE Historical_Era_Reference (
References_Id INT (4),
Historical_Era_Id INT (4),
FOREIGN KEY (Reference_Id) REFERENCES Reference (Reference_Id),
FOREIGN KEY (Historical_Era_Id) REFERENCES Historical_Era (Historical_Era_Id));
CREATE TABLE Loan_Item (
Item_Id INT (4),
Loan_Id INT (4),
FOREIGN KEY (Item_Id) REFERENCES Items(Item_Id),
FOREIGN KEY (Loan_Id) REFERENCES Loan(Loan_Id));
CREATE TABLE Geographic_Area (
Geo_Area_Id INT (4),
Geo_Area_Name VARCHAR (30),
Region_Id INT (4),
PRIMARY KEY (Geo_Area_Id),
FOREIGN KEY (Region_Id) REFERENCES Region (Region_Id));
CREATE TABLE Loan (
Loan_Id INT (4),
Item_Id INT (4)
Organisation_Id INT(4)
Loan_Start DAY,
Loan_End DAY
FOREIGN KEY (Organisation_Id) REFERENCES Organisation (Organisation_Id),
FOREIGN KEY (Item_Id) REFERENCES Items (Item_Id));

Try to create the tables first and add the Foreign Keys later.

There are plenty of issues with the query above.
You are making a reference to a table which doesn't exist yet: "FOREIGN KEY (Geo_Area_Id) REFERENCES Geographic_Area(Geo_Area_Id));" First create the table and then update the foreign keys.
There are plenty of syntax errors - missing commas and double brackets. Instead of pointing them one by one, I'd suggest learning how to spot them, for example I suggest using an IDE. I personally test statements in MySQL Workbench.
The query will likely produce an error 150, for a number of reasons. Please see a very good summary on typical errors with primary keys as FK in the first answer here.

Related

Error Code 3078 - Foreign Key not compatible - what does this even mean?

I keep getting this Error code:
Alter Table PAYMENT add FOREIGN KEY (CustomerId)REFERENCES CUSTOMER(CustomerId) Error Code: 3780. Referencing column 'CustomerId' and referenced column 'CustomerId' in foreign key constraint 'payment_ibfk_7' are incompatible. 0.0010 sec
I don't know how to fix it. Please Help.
Create Schema IF NOT EXISTS AUTOMOBILE_COMPANY;
USE AUTOMOBILE_COMPANY;
CREATE TABLE IF NOT EXISTS CUSTOMER(
CustomerId INT NOT NULL PRIMARY KEY,
CustomerFname VARCHAR(30) NOT NULL,
CustomerLname VARCHAR(30) NOT NULL,
CustomerPhone VARCHAR(15) NOT NULL UNIQUE,
CustomerGender VARCHAR(10),
CustomerYearly_salary VARCHAR(15),
CustomerStreet VARCHAR (30),
CustomerCity VARCHAR (30),
CustomerState VARCHAR(30),
CustomerPostcode VARCHAR(6),
ProductId INT NOT NULL,
PaymentId INT
);
CREATE TABLE IF NOT EXISTS DEALERS(
DealerName VARCHAR (10)NOT NULL PRIMARY KEY,
DealerBrand VARCHAR (7),
DealerModel VARCHAR (4),
DealerColour VARCHAR (5),
DealerAvailability VARCHAR (12),
DealerSalesByDate Date,
DealerCarEngine VARCHAR (17),
DealerTransmission VARCHAR (16),
DealerBodyStyle VARCHAR (20)
);
CREATE TABLE IF NOT EXISTS EMPLOYEE(
EmployeeSsn INT NOT NULL PRIMARY KEY,
EmployeeFirst_name VARCHAR(20) NOT NULL,
EmployeeLast_name VARCHAR(20) NOT NULL,
EmployeeBirthday INT NOT NULL,
EmployeeStreet VARCHAR (30),
EmployeeCity VARCHAR (30),
EmployeePostcode VARCHAR(6),
EmployeeState VARCHAR(30),
EmployeeSalary DECIMAL(6) NOT NULL,
EmplyeeSex VARCHAR(6)
);
CREATE TABLE IF NOT EXISTS PAYMENT(
PaymentId INT PRIMARY KEY,
Bank VARCHAR (30) NOT NULL,
CustomerId INT,
EmployeeSsn INT ,
Amount DECIMAL(7)NOT NULL,
PaymentDate DATETIME NOT NULL,
ProductId INT NOT NULL
);
CREATE TABLE IF NOT EXISTS PRODUCT(
ProductId INT NOT NULL PRIMARY KEY,
ArticleNumber VARCHAR (30)NOT NULL,
brand VARCHAR (7),
model VARCHAR (4),
colour VARCHAR (5),
availability VARCHAR (12),
CustomerId INT NOT NULL,
StoreId INT NOT NULL,
CarEngine VARCHAR (17),
Transmission VARCHAR (16),
BodyStyle VARCHAR (20)
);
ALTER TABLE CUSTOMER ADD FOREIGN KEY (productid) REFERENCES PRODUCT(productid);
ALTER TABLE CUSTOMER ADD FOREIGN KEY (paymentid) REFERENCES PAYMENT(paymentid);
CREATE TABLE IF NOT EXISTS RENTAL(
RentalId INT NOT NULL PRIMARY KEY,
RentalDate DATETIME NOT NULL,
ReturnDate DATETIME NOT NULL,
CustomerId INT NOT NULL,
EmployeeSsn INT NOT NULL
);
CREATE TABLE IF NOT EXISTS MANUFACTURER(
StoreId INT NOT NULL PRIMARY KEY,
Street VARCHAR (30)NOT NULL,
City VARCHAR (30)NOT NULL,
State VARCHAR(30)NOT NULL,
Postcode VARCHAR(6)NOT NULL,
ArticleNumber VARCHAR (30)NOT NULL,
SupplierParts VARCHAR (20) NOT NULL
);
CREATE TABLE IF NOT EXISTS STORE (
StoreId INT NOT NULL PRIMARY KEY,
StoreStreet VARCHAR (30)NOT NULL,
StoreCity VARCHAR (30)NOT NULL,
StoreState VARCHAR(30)NOT NULL,
StorePostcode VARCHAR(6)NOT NULL,
StoreManager_staff VARCHAR(30)
);
CREATE TABLE IF NOT EXISTS SUPPLIER(
SupplierParts VARCHAR (20) NOT NULL PRIMARY KEY,
SupplierArticle_number INT NOT NULL
);
Alter Table PAYMENT add FOREIGN KEY (ProductId) REFERENCES PRODUCT(ProductId);
Alter Table PAYMENT add FOREIGN KEY (CustomerId)REFERENCES CUSTOMER(CustomerId);
Alter Table PAYMENT add FOREIGN KEY (EmployeeSsn)REFERENCES EMPLOYEE(EmployeeSsn);
ALTER TABLE RENTAL ADD FOREIGN KEY (EmployeeSsn) REFERENCES EMPLOYEE(EmplyeeSsn);
ALTER TABLE MANUFACTURER ADD FOREIGN KEY (ArticleNumber)REFERENCES PRODUCT(ArticleNumber);
ALTER TABLE MANUFACTURER ADD FOREIGN KEY (SupplierParts) REFERENCES SUPPLIER(SupplierParts) ;
ALTER TABLE SUPPLIERS ADD FOREIGN KEY (SupplierParts)REFERENCES MANUFACTURER(SupplierParts);
ALTER TABLE STORE ADD FOREIGN KEY (EmployeeSsn) REFERENCES EMPLOYEE(EmployeeSsn) ;
ALTER TABLE STORE ADD FOREIGN KEY (SupplierParts) REFERENCES SUPPLIER(SupplierParts) ;
ALTER TABLE PRODUCT ADD FOREIGN KEY (CustomerId) REFERENCES CUSTOMER(CustomerId);
ALTER TABLE PRODUCT ADD FOREIGN KEY (StoreId) REFERENCES MANUFACTURER (StoreId);
ALTER TABLE RENTAL ADD FOREIGN KEY (CustomerId) REFERENCES CUSTOMER(CustomerId);
ALTER TABLE RENTAL ADD FOREIGN KEY (EmployeeSsn) REFERENCES EMPLOYEE(EmployeeSsn);
ALTER TABLE MANUFACTURER ADD FOREIGN KEY (ArticleNumber)REFERENCES PRODUCT(ArticleNumber);
ALTER TABLE MANUFACTURER ADD FOREIGN KEY (SupplierParts)REFERENCES SUPPLIER(SupplierParts);
The code you have posted has a few typo's/errors:
-- references "EmplyeeSsn" instead of "EmployeeSsn"
ALTER TABLE RENTAL ADD FOREIGN KEY (EmployeeSsn) REFERENCES EMPLOYEE(EmplyeeSsn);
-- ArticleNumber is not defined as unique in PRODUCT, can be resolved by adding a unique
-- constraint to PRODUCT on the column ArticleNumber
ALTER TABLE MANUFACTURER ADD FOREIGN KEY (ArticleNumber)REFERENCES PRODUCT(ArticleNumber);
-- Supplier parts is not unique in MANUFACTURER, it is the primary key of SUPPLIERS though
-- So this may be the wrong way round
ALTER TABLE SUPPLIERS ADD FOREIGN KEY (SupplierParts)REFERENCES MANUFACTURER(SupplierParts);
-- STORE contains neither a column called "EmployeeSsn" or "SupplierParts"
ALTER TABLE STORE ADD FOREIGN KEY (EmployeeSsn) REFERENCES EMPLOYEE(EmployeeSsn) ;
ALTER TABLE STORE ADD FOREIGN KEY (SupplierParts) REFERENCES SUPPLIER(SupplierParts) ;
Once all of the above errors are corrected, your code does not through an error, and the foreign key on customer is created correctly:
https://www.db-fiddle.com/f/dVrG7Re6r68jaqYJ8HfR4P/0
From what I am seeing through your script you have 2 issues:
1st - You have a circular reference between the Payment and Customer tables. The Customer table is referencing the Payment table using the PaymentId foreign key, and the Payment table is referencing the Customer table using the CustomerId foreign key. You need to remove one of them so you'll eliminate the circular reference. If I were you I would remove the 1st one since you will most probably have multiple payments per customer but only one customer per payment. So keep the following script:
ALTER TABLE PAYMENT ADD FOREIGN KEY (CustomerId) REFERENCES CUSTOMER(CustomerId);
And remove this:
ALTER TABLE CUSTOMER ADD FOREIGN KEY (paymentid) REFERENCES PAYMENT(paymentid);
2nd - You are creating another circular reference when using the Product table because you are combining the product table with the customer and the payment tables twice. Here again you ideally would have a scenario where 1 customer uses multiple payments to pay for multiple products they are buying. So you don't need the following foreign key:
ALTER TABLE PRODUCT ADD FOREIGN KEY (CustomerId) REFERENCES CUSTOMER(CustomerId);
The reason for doing is because you only need one key to build a relationship between two tables. With regards to the 2nd point, you don't need to create a reference between the customer and the product because is already inferred in the two previous relationships you created; that between the Customer and the Payment and the other between the Payment and the Product. So there is a chained relationship which correlates the Customer to the Product they bought.

mySQL trying to create table with constraint foreign key

I have this simple code
create table transport (
CODE varchar (10),
TDATE date,
ID integer,
PNAME varchar (10),
primary key (CODE,TDATE,ID,PNAME) );
create table planes (
NAME varchar (10),
NSEATS integer,
FSEATS integer,
ECSEATS integer,
primary key (NAME),
CONSTRAINT foreign key(NAME) references transport(PNAME));
But it doesn't let me do the foreign key thing as it says errno: 150 "Foreign key constraint is incorrectly formed
Any tips appreciated
Thanks
The use of composite primary keys in this case is not reasonable. If you want a foreign key reference, you need to reference all columns in the primary key. So, this version is simpler:
create table transport (
transportId int not null auto_increment primary key,
CODE varchar (10),
TDATE date,
ID integer,
PNAME varchar (10),
unique (CODE, TDATE, ID, PNAME)
);
create table planes (
planeId int not null auto_increment primary key,
NAME varchar (10),
NSEATS integer,
FSEATS integer,
ECSEATS integer,
primary key (NAME),
transportId int,
CONSTRAINT foreign key(transportId) references transport(transportId)
);
Rule is that : A Foreign key in one table points to a Primary Key in another table.

SQL: A query that verify referential integrity across all tables

I have created my tables and populated it but I am not sure how to write a query to verify the referential integrity across all tables.
This is what I need:
SELECT lists all primary keys
FROM lists all tables
WHERE shows all relationships
This is what I have so far:
SELECT
categId, zipCode, suppId, acctId, prodId, orderId
From
CATEGORY, ZIP, SUPPLIER, ACCOUNT, SUPPLIER_REGION, PRODUCT, PROD_DETAIL, ORDERX, ORDER_LINE_ITEM
I am not sure what to put for WHERE.
My professor wants a command to verify the referential integrity. There are a lot of other stuff he wants but this is the only thing I am not sure how to do.
I added my tables.
create table CATEGORY (
categId varchar (8),
categIdParent varchar (8),
constraint CATEGORY_PK primary key (categId),
constraint CATEGORY_FK foreign key (categIdParent) references CATEGORY (categId)
);
create table ZIP(
zipCode int (5),
city varChar (16),
state varChar (16),
constraint ZIP_PK primary key (zipCode)
);
create table SUPPLIER (
supplId int (9),
supplName varChar (24),
supplStatus varChar (16),
supplYearEstabl date,
zipCode int (5),
constraint SUPPLIER_PK primary key (supplId),
constraint SUPPLIER_FK Foreign Key (zipCode) references ZIP (zipCode)
);
CREATE TABLE SUPPLIER_REGION (
supplId int (9),
region varChar (24),
constraint SUPPLIER_REGION_PK primary key (supplId, region),
constraint SUPPLIER_REGION_FK foreign key (supplId) references SUPPLIER (supplId)
);
create table PRODUCT (
prodId int (11),
prodDescr varChar (256),
prodType varChar (12),
prodModel Char (16),
prodPlaceOrigin Char (16),
prodPrice decimal (10,2),
prodMinQty int (8),
supplId int (9),
categId varchar (8),
constraint PRODUCT_PK primary key (prodId),
constraint PRODUCT_FK1 foreign key (supplId) references SUPPLIER (supplId),
constraint PRODUCT_FK2 foreign key (categId) references CATEGORY (categId)
);
create table PROD_DETAIL (
prodId int (11),
prodDetailNo int (8),
prodDetailName varChar (32),
prodDetailValue decimal (10,2),
constraint PROD_DETAIL_PK primary key (prodID, prodDetailNo),
constraint PROD_DETAIL_FK foreign key (prodID) references PRODUCT (prodID)
);
create table ACCOUNT (
acctId varchar(50),
acctName varChar (24),
acctDept varChar (16),
acctTitle varChar (16),
acctGender Char (1),
acctEmail varChar (24),
acctAddr varChar (24),
zipCode int (5),
acctPhone int (11),
constraint ACCOUNT_PK primary key (acctId),
constraint ACCOUNT_FK foreign key (zipCode) references ZIP (zipCode)
);
create table ORDERX (
orderId int (8),
orderPayMethod varChar (16),
orderShipDate date,
acctId varchar (50),
constraint ORDER_PK primary key (orderId),
constraint ORDER_FK foreign key (acctId) references ACCOUNT (acctId)
);
create table ORDER_LINE_ITEM (
orderId int (8),
orderLineNo int (8),
orderLineQty int (8),
orderLineUnit int (8),
orderLinePrice decimal (10,2),
prodId int (11),
constraint ORDER_LINE_ITEM_PK primary key (orderId, orderLineNo),
constraint ORDER_LINE_ITEM_FK1 foreign key (orderId) references ORDERX (orderId),
constraint ORDER_LINE_ITEM_FK2 foreign key (prodId) references PRODUCT (prodId)
);
For SQL Server one good way is to create a diagram in SSMS. As you place each table into the diagram the FK relationships will be rendered as lines between tables and primary keys will be displayed as "key" icons.

MYSQL designing query issue

I am trying to create a query that shows the name and adress of all people who have incurred fines but do not have a driving license. (So do not show up in the driving license table) How would I go about including something who does not show up in a table?
Here are my tables
CREATE TABLE offences (
oOffenceID VARCHAR (30),
oDescription VARCHAR (200),
oMaximumFine INT (10),
CONSTRAINT o_pk
PRIMARY KEY (oOffenceID)
);
CREATE TABLE drivers (
dPersonID VARCHAR (30),
dLicenseNumber INT (20),
dLicenseRemoved ENUM('yes','no'),
dExpiryDate DATE,
CONSTRAINT d_pk
PRIMARY KEY (dLicenseNumber),
CONSTRAINT d_fk
FOREIGN KEY (dPersonId)
REFERENCES People (pPersonID)
);
CREATE TABLE people (
pPersonID VARCHAR (30),
pName VARCHAR (30),
pAddress VARCHAR (50),
pNIN VARCHAR (30),
CONSTRAINT p_pk
PRIMARY KEY (pPersonID)
);
CREATE TABLE vehicle (
vOwnerID VARCHAR (30),
vColour VARCHAR (30),
vModel VARCHAR (30),
vMake VARCHAR (30),
vVehicleID VARCHAR (30),
CONSTRAINT v_pk
PRIMARY KEY (vVehicleID),
CONSTRAINT v_fk
FOREIGN KEY (vOwnerID)
REFERENCES People (pPersonID)
);
CREATE TABLE fines (
fFineID INT (30) AUTO_INCREMENT,
fVehicleID VARCHAR (30),
fPersonID VARCHAR (30),
fTime DATE,
fAmount INT (10),
fOfficerStatement VARCHAR (500),
fOffenceID VARCHAR (30),
CONSTRAINT f_pk
PRIMARY KEY (fFineID),
CONSTRAINT f_fk
FOREIGN KEY (fVehicleID)
REFERENCES vehicle (vVehicleID),
CONSTRAINT f_fk1
FOREIGN KEY (fPersonID)
REFERENCES people (pPersonID),
CONSTRAINT f_fk2
FOREIGN KEY (fOffenceID)
REFERENCES offences (oOffenceID)
);
So far I have
SELECT DISTINCT pName, pAddress
FROM people, fines, drivers
WHERE
pPersonID <> dPersonID
AND
pPersonID = fPersonID
AND
fAmount > 0
but this doesn't remove all the necessary data.
Any help or guidance of the right tools to use would be much appreciated.
Use a LEFT JOIN and check for NULL values
example:
SELECT *
FROM
table_A
LEFT JOIN table_B
ON table_A.id = table_b.a_id
WHERE table_B.a_id IS NULL

Problem with foreign keys in sql database

I have a school assignment that that is giving me and my friends headaches... So this is my queries that i have executed, one at a time ofc...
CREATE DATABASE GamblingSociety;
USE GamblingSociety;
CREATE TABLE GamblingDen
(
Name VARCHAR (20) PRIMARY KEY,
Address VARCHAR (50),
Phone VARCHAR (10)
);
CREATE TABLE Room (
RoomNr INT,
GameCapaity INT,
GamblingDenName VARCHAR (20),
PRIMARY KEY (RoomNr, GamblingDenName),
FOREIGN KEY (GamblingDenName) REFERENCES GamblingDen (Name)
);
CREATE TABLE Employee (
SSN CHAR (11) PRIMARY KEY,
Name VARCHAR (20),
Address VARCHAR(50),
Salary INT,
isBoss BOOL,
GamblingDenName VARCHAR (20),
FOREIGN KEY (GamblingDenName) REFERENCES GamblingDen (Name)
);
CREATE TABLE GameType (
Name VARCHAR (20) PRIMARY KEY,
WinningProcentage FLOAT,
ResponsibleEmployee CHAR (11),
FOREIGN KEY (ResponsibleEmployee) REFERENCES Employee (SSN)
);
CREATE TABLE Supplier (
Name VARCHAR (20) PRIMARY KEY,
Address VARCHAR (50)
);
CREATE TABLE SupplierOfGameType (
SupplierName VARCHAR (20),
GameTypeName VARCHAR (20),
PRIMARY KEY(SupplierName, GameTypeName),
FOREIGN KEY (SupplierName) REFERENCES Supplier (Name),
FOREIGN KEY (GameTypeName) REFERENCES GameType (Name)
);
CREATE TABLE GamblingTable (
TableNr INT,
RoomNr INT,
GamblingDenName VARCHAR (20),
GameTypeName VARCHAR (20),
Comments VARCHAR (128),
PRIMARY KEY (RoomNr, TableNr, GamblingDenName, GameTypeName),
FOREIGN KEY (RoomNr, GamblingDenName) REFERENCES Room (RoomNr, GamblingDenName),
FOREIGN KEY (GameTypeName) REFERENCES GameType (Name)
);
CREATE TABLE Shylock (
Phone CHAR (10) PRIMARY KEY,
Name VARCHAR (20),
Contry CHAR (3)
);
CREATE TABLE Customer (
SSN CHAR (11) PRIMARY KEY,
Name VARCHAR (20),
Phone CHAR (10),
Address VARCHAR (50)
);
But this last query does not work:
USE GamblingSociety;
CREATE TABLE GamblingInstance (
StartTime DATETIME,
EndingTime DATETIME,
GamblingDenName VARCHAR (20),
TableNr INT,
GameTypeName VARCHAR (20),
Customer CHAR (11),
Shylock CHAR (10),
Debt INT,
DebtPayed BOOL,
DebtPayedDate DATETIME,
PRIMARY KEY (StartTime, GameTypeName, Customer),
FOREIGN KEY (GamblingDenName, TableNr, GameTypeName) REFERENCES GamblingTable (GamblingDenName, TableNr, GameTypeName),
FOREIGN KEY (Customer) REFERENCES Customer (SSN),
FOREIGN KEY (Shylock) REFERENCES Shylock (Phone)
);
It gives me this error:
"Error Code: 1005. Can't create table 'gamblingsociety.gamblinginstance' (errno: 150)"
if I replace this:
FOREIGN KEY (GamblingDenName, TableNr, GameTypeName) REFERENCES GamblingTable (GamblingDenName, TableNr, GameTypeName),
with this:
FOREIGN KEY (GameTypeName) REFERENCES GamblingTable (GameTypeName),
It works, so it's something with the GamblingDenName and TableNr.
And i have google it and found a lot of tips, but nothing yeat have worked...
So anyone with any idea?
Thanks in advance!
There is no key in GamblingTable that can satisfy this REFERENCE:
REFERENCES GamblingTable (GamblingDenName, TableNr, GameTypeName),
That is, there is no key in GamblingTable for which GamblingDenName, TableNr, GameTypeName are the only columns, or the first three columns.
There is a key that satisfies REFERENCES GamblingTable (GameTypeName), which is why that version works.
(I have to say that I've never actually seen FOREIGN KEYs being used to parent other FOREIGN KEYs, but I guess it works).