Creating a SQL database script for fictional restaurant - sql

im making a fictional database for a ficitonal restaurant. I managed to write most of SQL script myself and it works. Like creating tables, inserting fake data. However I am not sure how to connect a meal to an order and table, and bill to a meal, and all of that to a customer.
Here is my script (the commented out foreign keys are what i dont know how to connect, or how to edit them so its all connected as i mentioned above):
DROP DATABASE IF EXISTS restaurantDB;
CREATE DATABASE restaurantDB;
USE restaurantDB;
CREATE TABLE `bill` (
`billID` int NOT NULL AUTO_INCREMENT,
`payAmount` varchar(6) NOT NULL,
PRIMARY KEY (`billID`)
);
INSERT INTO `bill` VALUES (1, '$258');
CREATE TABLE `customer` (
`customerID` int NOT NULL AUTO_INCREMENT,
`firstName` varchar(255) NOT NULL,
`lastName` varchar(255) NOT NULL,
`phone` varchar(20) NOT NULL,
PRIMARY KEY (`customerID`)
);
INSERT INTO `customer` VALUES (1, 'Bruce', 'Lee', '420420589');
CREATE TABLE `meal` (
`mealID` int NOT NULL AUTO_INCREMENT,
`sides` varchar(255) NULL,
`main` varchar(255) NULL,
`beverage` varchar(255) NOT NULL,
PRIMARY KEY (`mealID`)
);
INSERT INTO `meal` VALUES (1, 'potatos', 'steak', 'wine');
CREATE TABLE `order` (
`orderID` int NOT NULL,
`time` datetime(2) NOT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`orderID`)
);
INSERT INTO `order` VALUES (1, '21-09-27 13:36:06');
CREATE TABLE `reservation` (
`reservationID` int NOT NULL AUTO_INCREMENT,
`checkIn` datetime(2) NOT NULL,
`checkOut` datetime(2) NOT NULL,
PRIMARY KEY (`reservationID`)
);
INSERT INTO `reservation` VALUES (1, '21-09-27 13:24:06', '21-09-27 14:17:23');
CREATE TABLE `table` (
`tableID` int NOT NULL AUTO_INCREMENT,
`numOfSeats` int NOT NULL,
PRIMARY KEY (`tableID`)
);
INSERT INTO `table` VALUES (1, 1);
/* ALTER TABLE `table` ADD CONSTRAINT `fk_bill_table_1` FOREIGN KEY (`tableID`) REFERENCES `table` (`billID`);
ALTER TABLE `order` ADD CONSTRAINT `fk_order_table_1` FOREIGN KEY (`orderID`) REFERENCES `table` (`tableID`);
ALTER TABLE `order` ADD CONSTRAINT `fk_order_meal_1` FOREIGN KEY (`orderID`) REFERENCES `meal` (`mealID`);
ALTER TABLE `order` ADD CONSTRAINT `fk_order_bill_1` FOREIGN KEY (`orderID`) REFERENCES `bill` (`billID`);
ALTER TABLE `reservation` ADD CONSTRAINT `fk_reservation_customer_1` FOREIGN KEY (`reservationID`) REFERENCES `customer` (`customerID`);
ALTER TABLE `table` ADD CONSTRAINT `fk_table_reservation_1` FOREIGN KEY (`tableID`) REFERENCES `reservation` (`reservationID`); */
Here is also a picture of the diagram (not sure if it makes sense connected like i have it currently tho):
Thanks to anyone who will be able to explain and help make the connections.

Okay, so finally got it working. Thanks #Austin.
Actually the only issue I had was with the datetime(2) it was just supposed to say datetime.
However #Austin showed me a better alternative, so I will create also a second, extended database with the relations #Austin suggested and add onto that.

Related

#1452 - Cannot add or update a child row: a foreign key constraint fails Policy_payment

enter image description hereI have created these tables in phpmyadmin
Payment table
DROP TABLE IF EXISTS Payment;
CREATE TABLE IF NOT EXISTS Payment (
pay_id int(5) NOT NULL,
number int(25) default NULL,
amount decimal(20,2) default NULL,
CONSTRAINT Payment_pk_payid
PRIMARY KEY (pay_id) )
ENGINE=InnoDB DEFAULT CHARSET=utf8;
Policy_payment table
DROP TABLE IF EXISTS Policy_payment;
CREATE TABLE IF NOT EXISTS Policy_payment(
id int(5) NOT NULL,
policy_id int(5) NOT NULL,
pay_id int(5) NOT NULL,
date date default NULL,
CONSTRAINT Policy_payment_pk_id_policyid_payid
PRIMARY KEY (id,policy_id,pay_id),
CONSTRAINT Policy_payment_fk_policyid
FOREIGN KEY (policy_id)
REFERENCES Policy (policy_id),
CONSTRAINT Policy_payment_fk_payid
FOREIGN KEY (pay_id)
REFERENCES Payment (pay_id) )
ENGINE=InnoDB DEFAULT CHARSET=utf8;
So when i try to insert the the values in Policy_payment table, it gives a #1452 error. What am i doing wrong?
--Dumping data for table Policy_payment
INSERT INTO Policy_payment (
id, policy_id, pay_id, date)
VALUES
('70111', '88881', '20001', '2019-01-10'),
('70112', '88882', '20002', '2019-09-25'),
('70113', '88883', '20003', '2019-04-18'),
('70114', '88884', '20004', '2020-11-11'),
('70115', '88885', '20005', '2020-06-23'),
('70116', '88886', '20006', '2021-12-11'),
('70117', '88887', '20007', '2021-08-20'),
('70118', '88888', '20008', '2018-03-04'),
('70119', '88889', '20009', '2018-03-20'),
('70110', '88810', '20010', '2016-02-09');
enter image description here
this is the error
#1452 - Cannot add or update a child row: a foreign key constraint fails (S11185754.Policy_payment, CONSTRAINT Policy_payment_fk_payid FOREIGN KEY (pay_id) REFERENCES Payment (pay_id))
Thanks
You are trying to insert a record with a pay_id that doesn't match any record in the payment table i.e. exactly what the error message says.

Making a Database table in SQL, weird error

This is the code for the Database.Its giving me an error that for every TABLE created something has already taken that name, one of the error messages is at the end of the post.
COMMIT;
CREATE TABLE Team (
Team_ID INTEGER GENERATED ALWAYS AS IDENTITY,
Team_Name NVARCHAR2(40) NOT NULL,
Team_Manager VARCHAR(20),
CONSTRAINT kkeyconst PRIMARY KEY(Team_ID)
);
COMMIT;
insert into Team(TEAM_NAME, TEAM_MANAGER) VALUES ('Red Sox', 'Jon');
insert into Team(TEAM_NAME, TEAM_MANAGER) VALUES('White Sox', 'Tony');
CREATE TABLE Driver (
Driver_id INTEGER NOT NULL,
Teams_ID INTEGER,
Driver_age INTEGER,
Driver_Name NVARCHAR2(20) NOT NULL,
CONSTRAINT DriverAge CHECK (Driver_age BETWEEN '19' AND '65'),
CONSTRAINT driverpk PRIMARY KEY(Driver_ID),
CONSTRAINT Teams_PK FOREIGN KEY (Teams_ID) REFERENCES Team(Team_ID)
);
COMMIT;
insert into Driver(DRIVER_AGE,DRIVER_NAME) VALUES ('21', 'Jon');
insert into Driver(DRIVER_AGE, DRIVER_NAME) VALUES ('20', 'Tony');
CREATE TABLE Participation (
TeamName_ID INTEGER,
Driver_ID INTEGER,
PointsEarned INTEGER,
CONSTRAINT TeamName_FK FOREIGN KEY (TeamName_ID) REFERENCES Team(Team_ID),
CONSTRAINT Driver_FK FOREIGN KEY(Driver_ID) REFERENCES Driver(Driver_ID)
);
COMMIT;
insert into Participation(PARTICIPATION_POINTS_EARNED) VALUES (150);
CREATE TABLE Finish (
Racer_ID INTEGER,
Finish_Position INTEGER NOT NULL,
Fishish_Result VARCHAR(50) NOT NULL,
CONSTRAINT Racer_FK FOREIGN KEY (Racer_ID) REFERENCES Driver(Driver_id)
);
COMMIT;
insert into Finish(Finish_POSITION, Finish_RESULT) VALUES ('1', 'Winner');
insert into Finish(Finish_POSITION, Finish_RESULT) VALUES ('3', 'Third Place');
CREATE TABLE RaceComponent (
RC_ID INTEGER NOT NULL,
Driver1_ID INTEGER,
RC_Type VARCHAR(25),
CONSTRAINT Rcpk PRIMARY KEY(RC_ID),
CONSTRAINT Driver1_FK FOREIGN KEY (Driver1_ID) REFERENCES Driver(Driver_ID)
);
COMMIT;
insert into RaceComponent(RC_TYPE) VALUES ('Hot Wheels');
insert into RaceComponent(RC_TYPE) VALUES ('Tonka');
CREATE TABLE Race (
Race_Id INTEGER,
RC_ID INTEGER,
Race_Title VARCHAR(30) NOT NULL,
Race_Location VARCHAR(50) NOT NULL,
Race_Date DATE,
CONSTRAINT RACPEK PRIMARY KEY(RACE_ID),
CONSTRAINT RC_FK FOREIGN KEY (RC_ID) REFERENCES RaceComponent(RC_ID)
);
COMMIT;
insert into Race(RACE_TITLE, RACE_LOCATION, RACE_DATE) VALUES ('Tonys race', 'Moncton', DATE '2016-04-25');
insert into Race(RACE_TITLE, RACE_LOCATION, RACE_DATE) VALUES ('Mikes Racing', 'San-Francisco', DATE '2015-04-25');
ERROR:
Commit complete.
Error starting at line : 3 in command -
CREATE TABLE Team (
Team_ID INTEGER GENERATED ALWAYS AS IDENTITY,
Team_Name NVARCHAR2(40) NOT NULL,
Team_Manager VARCHAR(20),
CONSTRAINT kkeyconst PRIMARY KEY(Team_ID)
)
Error report -
SQL Error: ORA-00955: name is already used by an existing object
00955. 00000 - "name is already used by an existing object"
*Cause:
*Action:
Commit complete.
I thought it might be because I am calling the Foreign keys the same name as their primary key value, but im not 100% sure what is causing it.
If the table was created during an earlier run of your script, you will get that error. It is always good to check to see if your table already exists before trying to create it. Here is a good snippet of code from StackOverflow for checking to see if the table already exists or not.
IF (EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'TheSchema'
AND TABLE_NAME = 'TheTable'))
BEGIN
--Do Stuff
END

Model a Table that depends on a set of values in referenced table that can or not be present at the same time

I have a table 'medical_observations' that in one field references other table 'sypstoms_at_arriving' that describes a list of possible symptoms.
CREATE TABLE `patients`(
id_patient INTEGER NOT NULL PRIMARY KEY,
name VARCHAR(25) ,
address VARCHAR(50) ,
CONSTRAINT `uc_Info_Patient` UNIQUE (`id_patient`)
);
INSERT INTO `patients` values (1,'joe','joe´s address');
INSERT INTO `patients` values (2,'moe','moe´s address');
INSERT INTO `patients` values (3,'karl','karle´s address');
INSERT INTO `patients` values (4,'lenny','lenny´s address');
CREATE TABLE `symptoms_at_arrival` (
symptom_at_arrival varchar(30) primary key
);
INSERT INTO `symptoms_at_arrival` values ('vomit');
INSERT INTO `symptoms_at_arrival` values ('urine');
INSERT INTO `symptoms_at_arrival` values ('dizziness');
INSERT INTO `symptoms_at_arrival` values ('convulsion');
CREATE TABLE `medical_observations`(
id_medical_observation INTEGER NOT NULL PRIMARY KEY,
id_patient INTEGER NOT NULL,
symptom_at_arrival VARCHAR(30),
FOREIGN KEY (id_patient) references `patients` (id_patient),
FOREIGN KEY (symptom_at_arrival) references `symptoms_at_arrival` (symptom_at_arrival ),
CONSTRAINT `uc_Info_medical_Observation` UNIQUE (`id_medical_observation`,`id_patient`)
);
My doubt is how to model or store th case when patient has several symptoms... and not just one.
If that would be the case the name of symptom would be enough...
But if patient show several symptoms at the same time?
Update
I have done a sqlfiddle, I was thinking to add a kind of table with 1's and 0's representing if patient shows certain symptom... Would that be correct?
You'll have to make connection in the foreign keys
|patient| |medical_observations| |symptoms_at_arriving|
--------- ---------------------- ----------------------
**id** 1 ----| **id_medical_observation** |-----1 **id**
name |-M **id_patient** | symptom_at_arrival
**symptom_at_arrival** M---|
Try this, don't have mysql here to test, making table multi primary key to support multiple symptoms at same time
CREATE TABLE `symptoms_at_arriving` (
id integer not null primary key autoincrement,
symptom_at_arrival varchar(30)
);
INSERT INTO `symptom_at_arrival' values ('vomit');
INSERT INTO `symptom_at_arrival` values ('urine');
INSERT INTO `symptom_at_arrival` values ('dizziness');
INSERT INTO `symptom_at_arrival` values ('convulsion');
CREATE TABLE `medical_observations`(
id_medical_observation INTEGER NOT NULL,
id_patient INTEGER NOT NULL,
symptom_at_arrival integer not null,
FOREIGN KEY (id_patient) references `patients` (id_patient),
FOREIGN KEY (symptom_at_arrival) references `symptoms_at_arriving` (symptom_at_arrival,
PRIMARY KEY (id_medical_observation, id_patient, symptom_at_arrival)
);

Reusing a constraint while creating a table

While creating a table how can I reuse a constraint that has been mentioned for a previous column?
create table ticket_details(
from_stn char(3)
constraint chk check(from_stn in ('vsh','mas','ndl'))
constraint nn NOT NULL,
to_stn char(3)
constraint nn1 NOT NULL, (instead of crea)
seat_no number(3)
constraint PK primary key,
);
A domain constraint will be enforced on any instance of the domain. Also: upon change, you'll have to change it in only one place. (the syntax might differ slightly between implementations)
CREATE DOMAIN THE_STN CHAR(3) constraint THE_STN_check_da_value check(VALUE in ('vsh','mas','ndl'))
;
CREATE table ticket_details
( seat_no INTEGER NOT NULL PRIMARY KEY
, from_stn THE_STN NOT NULL
, to_stn THE_STN
);
INSERT INTO ticket_details(seat_no,from_stn,to_stn) VALUES (1, 'vsh', 'ndl' ); -- succeeds
INSERT INTO ticket_details(seat_no,from_stn,to_stn) VALUES (2, 'vsh', NULL ); -- succeeds
INSERT INTO ticket_details(seat_no,from_stn,to_stn) VALUES (2, 'lol', 'mas' ); -- fails
Reusing a constraint for another column is not possible. You have to define it for other column if you want

Removing all references from a tuple using Oracle/Access

I created a simple databse using Oracle that has several tables and a few constraints, i am using Access 2007 to interact with the database.
My problem is that I have a table that is called "Customer" which holds several fields, most notably a Primary Key called CUSTID.
I have another table called "Order" which uses the Primary Key in "Customer" as a Foreign Key.
Obviously if i try to delete a customer that is being used in "Order" i get an error as it's being used. This means i have to delete the particular order that references the Customer and then i can delete the Custome record.
I know that "cascade" should delete everything associated with it, my question is how can i do that from Access? I have limited knowledge of databases but enough to create one etc..
This is more of a validation thing, it's just a hassle to delete certain tuples before i can remove another.
This is the database created for Oracle:
--Used to create a "Clean" slate
DROP TABLE ITEM CASCADE CONSTRAINTS;
DROP TABLE CUSTOMER CASCADE CONSTRAINTS;
DROP TABLE CORDER CASCADE CONSTRAINTS;
DROP TABLE FORUM CASCADE CONSTRAINTS;
CREATE TABLE ITEM
(
ITEMID NUMBER(4) NOT NULL,
NAME CHAR(15) NOT NULL,
CATEGORY CHAR(15) NOT NULL,
PRICE NUMBER(8) NOT NULL,
CONSTRAINT ITEM_PK PRIMARY KEY (ITEMID)
);
INSERT INTO ITEM VALUES (1000,'CARROT SEEDS','PACKET SEEDS',2.99);
INSERT INTO ITEM VALUES (2250,'ROSES','FLOWERS',5.99);
INSERT INTO ITEM VALUES (3300,'TOMATOES','PACKET SEEDS',2.99);
INSERT INTO ITEM VALUES (4050,'POTATOES','PACKET SEEDS',1.99);
CREATE TABLE CUSTOMER
(
CUSTID NUMBER(4) NOT NULL,
FNAME CHAR(10) NOT NULL,
LNAME CHAR(10) NOT NULL,
ADDRESS CHAR(40) NOT NULL,
CITY CHAR(15) NOT NULL,
PCODE CHAR(7) NOT NULL,
CNUMBER NUMBER(11) NOT NULL,
CONSTRAINT CUSTOMER_PK PRIMARY KEY (CUSTID)
);
INSERT INTO CUSTOMER VALUES (1010,'JAMIE','KEELING','149 OLD MANSFIELD ROAD','DERBY','DE214SA',07500966490);
INSERT INTO CUSTOMER VALUES (2020,'HELEN','DARLINGTON','27 MOORPARK AVENUE','ROCHDALE','OL113JQ',07890189802);
INSERT INTO CUSTOMER VALUES (3030,'STEVEN','SEGAL','123 FAKE STREET','OHIO','SE095BG',01559345467);
INSERT INTO CUSTOMER VALUES (4040,'BRUCE','WAYNE','17 LAKEVIEW CRESCENT','CHICAGO','MN432BD',07500966490);
CREATE TABLE CORDER
(
ORDERID NUMBER(4) NOT NULL,
CUSTID NUMBER(4) NOT NULL,
SHIPADD CHAR(40) NOT NULL,
SHIPPCODE CHAR(7) NOT NULL,
SHIPDATE DATE,
ITEMID NUMBER(4) NOT NULL,
QUANTITY NUMBER(3) NOT NULL,
TOTAL NUMBER(8) NOT NULL,
CONSTRAINT ORDER_PK PRIMARY KEY (ORDERID),
CONSTRAINT FK_CUSTOMER FOREIGN KEY (CUSTID) REFERENCES CUSTOMER(CUSTID),
CONSTRAINT FK_ITEM FOREIGN KEY (ITEMID) REFERENCES ITEM(ITEMID)
);
INSERT INTO CORDER VALUES (1000,1010,'149 OLD MANSFIELD ROAD','DE214SA','12-JAN-07',1000,100,100.00);
INSERT INTO CORDER VALUES (2000,2020,'27 MOORPARK AVENUE','OL113JQ','04-NOV-10',2250,200,100.00);
INSERT INTO CORDER VALUES (3000,3030,'123 FAKE STREET','SE095BG','30-OCT-08',3300,150,100.00);
INSERT INTO CORDER VALUES (4000,4040,'17 LAKEVIEW CRESCENT','MN432BD','25-JUL-07',4050,125,100.00);
CREATE TABLE FORUM
(
FORUMID NUMBER(4) NOT NULL,
TITLE CHAR(30) NOT NULL,
THREADNAME CHAR(30) NOT NULL,
POSTER CHAR(20) NOT NULL,
POSTDATE DATE,
CONSTRAINT FORUM_PK PRIMARY KEY (FORUMID)
);
INSERT INTO FORUM VALUES (1001,'GENERAL CHAT','BEGINNER QUESTIONS','JAMIE KEELING', '25-NOV-09');
INSERT INTO FORUM VALUES (2002,'OFF TOPIC','FAVOURITE BAND','HELEN DARLINGTON', '12-JAN-09');
INSERT INTO FORUM VALUES (3003,'GENERAL CHAT','WHEN TO HARVEST?','BRUCE WAYNE', '02-NOV-08');
INSERT INTO FORUM VALUES (4004,'OFF TOPIC','WHERE DO YOU LIVE?','STEVEN SEGAL', '13-JAN-08');
Standard SQL way to create foreign key with ON DELETE CASCADE is following. I don't know if Access supports this, but Oracle does have support for ON DELETE CASCADE.
alter table CORDER
add foreign key FK_CUSTOMER
references CUSTOMER(custid)
on delete cascade
If you are re-creating tables, you can also define the foreign keys with on delete cascade in table creation statement. i.e. replace this
CONSTRAINT FK_CUSTOMER FOREIGN KEY (CUSTID) REFERENCES CUSTOMER(CUSTID)
with this
CONSTRAINT FK_CUSTOMER FOREIGN KEY (CUSTID) REFERENCES CUSTOMER(CUSTID) ON DELETE CASCADE