I'm a complete beginner in sql and I am using mysql xampp server where I have a customers table and a bookings table . I use mysql data modeler with a ddl to generate the code that creates these tables .
This is how my 2 tables are created below:
BOOKING TABLE:
CREATE TABLE booking (
booking_id INTEGER NOT NULL,
b_city VARCHAR(30),
b_date DATETIME,
departure_date DATETIME,
arrival_date DATETIME,
dep_time DATETIME,
arr_time DATETIME,
seat_type VARCHAR(30),
flight_cost DOUBLE,
total_cost DOUBLE,
booking_state VARCHAR(2),
deposit DOUBLE,
price_remenant DOUBLE,
customer_customer_id VARCHAR(20) NOT NULL,
flight_id INTEGER,
customer_customer_id1 VARCHAR(20) NOT NULL //I don't know why this is created again
);
CREATE UNIQUE INDEX booking__idx ON
booking (
customer_customer_id
ASC );
ALTER TABLE booking ADD CONSTRAINT booking_pk PRIMARY KEY ( booking_id );
ALTER TABLE booking
ADD CONSTRAINT booking_customer_fk FOREIGN KEY ( customer_customer_id )
REFERENCES customer ( customer_id );
ALTER TABLE booking
ADD CONSTRAINT booking_customer_fkv2 FOREIGN KEY ( customer_customer_id1 )
REFERENCES customer ( customer_id );
CUSTOMER TABLE :
CREATE TABLE customer (
customer_id VARCHAR(20) NOT NULL,
first_name VARCHAR(20),
last_name VARCHAR(30),
booking_booking_id INTEGER NOT NULL
);
CREATE UNIQUE INDEX customer__idx ON
customer (
booking_booking_id
ASC );
ALTER TABLE customer ADD CONSTRAINT customer_pk PRIMARY KEY ( customer_id );
ALTER TABLE customer
ADD CONSTRAINT customer_booking_fk FOREIGN KEY ( booking_booking_id )
REFERENCES booking ( booking_id );
Now whenever I try to insert a customer in mysql xampp server with typing
INSERT INTO customer('customer_id')VALUE("1234");
I get the error #1452 - Cannot add or update a child row: a foreign key constraint fails (airline_db.customer, CONSTRAINT customer_booking_fk FOREIGN KEY (booking_booking_id) REFERENCES booking (booking_id)) which I have no idea why since the customer_id is the primary key and the Booking.customer_id the foreign key and I do not know why booking_id is included in this error
This is also how my entities look in data modeler :
I would really appreciate your help .
you can't insert such alues
CREATE TABLE customer (
customer_id VARCHAR(20) NOT NULL,
first_name VARCHAR(20),
last_name VARCHAR(30),
booking_booking_id INTEGER NOT NULL
);
Means that you have at least have to enter 1 booking_id which can't be NULL, but as you don't have a default values for it
Also a foreign key means that you have to have in booking such an id stored before you add a row in customers
Last you have a further problem, as you can only add a booking when you have a customer_id and vice versa , so get rid of the constraint in customer
Related
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.
This is the task:
Create a table payment with attributes: p_id, c_id, staff_id, amount, payment_date where p_id is primary key and c_id and staff_id is foreign key which refer to table customer and staff respectively. Display the p_id and staff_id from the table payment where payment_date is 8 august 2020
Please help I am getting this error even though my code seems right to me
create table payment(
p_id int primary key,
amount int,
payment_date date,
c_id int,
staff_id int
);
create table customer(
cus_id int primary key,
c_id int,
foreign key (c_id) references payment(c_id)
);
ERROR 1215 (HY000): Cannot add foreign key constraint
You have your foreign key relationship backwards. payment should have FK to customer and staff.
create table customer (
c_id int primary key,
-- other columns
);
create table staff (
s_id int primary key
-- other columns
);
create table payment(
p_id int primary key,
amount int,
payment_date date,
c_id int,
staff_id int,
foreign key (c_id) references customer(c_id),
foreign key (staff_id) references staff(s_id)
);
I'm trying to create a table that has a composite PK constraint using Rep_ID, Store_ID, and Quarter and I'm trying to create a FK constraint on Rep_ID and Store_ID
This is my statement:
CREATE TABLE REP_CONTRACTS(
Store_ID INT(8),
Name INT(5),
Quarter CHAR(3),
Rep_ID INT(5),
PRIMARY KEY (Rep_ID, Store_ID, Quarter),
Rep_ID INT REFERENCES BOOK_STORES(Rep_ID),
Store_ID INT REFERENCES BOOK_STORES(Store_ID)
);
These are my tables:
Book Stores:
Column Name Datatype Constraint Comments
Store_ID INT(8) PRIMARY KEY column
Name VARCHAR(30) Should be UNIQUE and NOT NULL
Contact VARCHAR(20)
Rep_ID INT(5)
Rep Contracts
Column Name DataType
Store_ID INT(8)
Name INT(5)
Quarter CHAR(3)
Rep_ID INT(5)
I have already created the book store table, I'm trying to create the rep contracts table
I also get the error Duplicate column name 'Rep_ID'. Add a differentiating column alias. when running this query
you are declaring REPID twice in the table, which is why you are getting the duplication error. You may also want to create the column "Store ID" before using it in the Primary Key Statement.
CREATE TABLE REP_CONTRACTS(
Store_ID INT(8),
Name INT(5),
Quarter CHAR(3),
Rep_ID INT(5) REFERENCES BOOK_STORES(Rep_ID),
Store_ID INT REFERENCES BOOK_STORES(Store_ID),
PRIMARY KEY (Rep_ID, Store_ID, Quarter)
);
it is giving me an syntax error but i cannot pinpoint what's wrong.
use test;
CREATE TABLE EMPLOYEE_EXPENSE
(
"EMP_EXP_ID" INT NOT NULL,
"EMP_ID" INT(5,0),
"YEAR" INT(4,0),
"MONTH" INT(2,0),
"EXPENSE_CLAIM" INT(7,2),
"APPROVED_AMT" INT(7,2),
"PAID_DATE" DATE,
CONSTRAINT "EMP_EXP_PK" PRIMARY KEY ("EMP_EXP_ID"),
CONSTRAINT "FK_EMPLOYEE" FOREIGN KEY ("EMP_ID") REFERENCES "EMPLOYEE" ("EMP_ID") ENABLE
);
mysql workbench shows red squibles under first EMP_EXP_ID.
here's employee table.
CREATE TABLE EMPLOYEE(
EMP_ID INT(5) NOT NULL,
FNAME VARCHAR(20),
LNAME VARCHAR(20),
DEPT_ID INT(5) NOT NULL,
MANAGER_EMP_ID INT(5),
SALARY INT(5),
HIRE_DATE DATE,
JOB_ID INT(3),
ACTIVE CHAR(1) DEFAULT 'Y' NOT NULL,
CONSTRAINT employee_pk PRIMARY KEY (EMP_ID)
);
Get rid of the quotes around the column identifiers. They are incorrect. Either use ticks or nothing at all.
use test;
CREATE TABLE EMPLOYEE_EXPENSE
(
EMP_EXP_ID INT NOT NULL,
EMP_ID INT(5,0),
YEAR INT(4,0),
MONTH INT(2,0),
EXPENSE_CLAIM INT(7,2),
APPROVED_AMT INT(7,2),
PAID_DATE DATE,
CONSTRAINT EMP_EXP_PK PRIMARY KEY (EMP_EXP_ID),
CONSTRAINT FK_EMPLOYEE FOREIGN KEY (EMP_ID) REFERENCES EMPLOYEE (EMP_ID) ENABLE
);
enter code hereI have some trouble with homework I got that I need to understand.
Ok so I have 4 tables,
1: costumer
2: order
3: orderedproduct
4. product .
They are linked by foreign key.
I need to make a unique constraint so that a costumer can only place 1 unique order per day. If the same costumer wants to order more on the same day, it has to be written on the already existing order.
TABLES:
costumer
CREATE TABLE COSTUMER (COSTUMERNR INT NOT NULL,
NAME VARCHAR(256),
CITY VARCHAR(256),
PRIMARY KEY (COSTUMERNR)) ENGINE=INNODB;
order
CREATE TABLE ORDER (ORDERNR INT NOT NULL,
ORDERDATE DATETIME,
PRIMARY KEY (ORDERNR)),
FOREIGN KEY (COSTUMERNR) REFERENCES COSTUMER(COSTUMERNR)
ON DELETE CASCADE) ENGINE=INNODB;
orderedproduct
CREATE TABLE ORDEREDPRODUCT (OPNR INT NOT NULL,
AMOUNT INT,
FOREIGN KEY (ORDERNR) REFERENCES ORDER(ORDERNR),
FOREIGN KEY (PRODUCTCODE) REFERENCES PRODUCT (PRODUCTCODE)
ON DELETE CASCADE,
CHECK (AMOUNT=>0)) ENGINE=INNODB;
product
CREATE TABLE PRODUCT (PRODUCTCODE INT NOT NULL,
NAME VARCHAR(256),
TYPE VARCHAR(256),
PRICE FLOAT,
STOCK INT,
PRIMARY KEY (PRODUCTCODE),
CHECK (AMOUNT=>0)) ENGINE=INNODB;
alter table order add unique index(orderdate, COSTUMERNR);
If you're able to split the datetime column into a date column and a time column, you can use a simple constraint:
CREATE TABLE ORDER (
ORDERNR INT NOT NULL,
ORDERDATE DATE,
ORDERTIME TIME,
...
CONSTRAINT [UniqueOrder] UNIQUE NONCLUSTERED
(
COSTUMERNR, ORDERDATE
)