Im new to sql, I wrote these create table statements and inserted data into them. in the coffee table shop_id and supplier_id are foreign keys for tables I have already inserted data into. When I do my select statement these two values are null. why is this?
shop_id and supplier_id are null
# CREATE TABLES
CREATE TABLE COFFEE_SHOP (
shop_id int NOT NULL ,
shop_name varchar(50),
city varchar(50),
state CHAR (2),
PRIMARY KEY (shop_id)
);
CREATE TABLE SUPPLIER (
supplier_id int NOT NULL ,
company_name varchar(50),
country varchar(30),
sales_contact_name varchar (50),
email varchar(50) NOT NULL,
PRIMARY KEY (supplier_id)
);
CREATE TABLE COFFEE (
coffee_id int NOT NULL ,
shop_id int,
supplier_id int,
coffee_name VARCHAR (30),
price_per_pound numeric(5,2),
PRIMARY KEY (coffee_id),
FOREIGN KEY (shop_id) REFERENCES COFFEE_SHOP(shop_id),
FOREIGN KEY (supplier_id) REFERENCES SUPPLIER(supplier_id)
);
CREATE TABLE EMPLOYEE (
employee_id int NOT NULL ,
FirstName varchar(30),
LastName varchar(30),
hire_date date,
job_title varchar(30),
shop_id int,
PRIMARY KEY(employee_id),
FOREIGN KEY (shop_id) REFERENCES COFFEE_SHOP(shop_id)
);
# INSERTION QUERIES
INSERT INTO COFFEE_SHOP (shop_id, shop_name, city,state)
VALUES ('45', 'Stavanger', 'Norway','fl');
INSERT INTO SUPPLIER (supplier_id, company_name, country,sales_contact_name,email)
VALUES ('25', 'lovanger', 'Forway','Tl','sql#gmail.com');
INSERT INTO COFFEE (coffee_id,coffee_name,price_per_pound )
VALUES ('15','espresso','15');
SELECT *
FROM COFFEE
Hey you are missing the concept of Foreign Key.
It is never for Foreign key to have the values directly from another table when you have defined Foreign key in first table.
what it simply means that you are tying two tables in order to make sure that no data is inserted in another table which doesn't have a reference key in first table.
To make it easier for you to understand, lets take your coffee table example.
Let's suppose you are trying to insert a row in Coffee table with a supplier Id which is not present in Supplier Table.
INSERT INTO COFFEE (coffee_id,coffee_name,price_per_pound,supplier_id )
VALUES ('15','espresso','15','111');
This will error out as
Schema Error: Error: ER_NO_REFERENCED_ROW_2: Cannot add or update a child row: a foreign key
constraint fails (`test`.`COFFEE`, CONSTRAINT `COFFEE_ibfk_2` FOREIGN KEY
(`supplier_id`) REFERENCES `SUPPLIER` (`supplier_id`))
Which means you can't insert any row in coffee table with Supplier Id which is not already present in Supplier table.
That's the whole fundamental of Foreign Key and it's use.
So that no corrupt data is inserted in tables.
This foreign key establishes referential integrity between Supplier and Coffee tables, thus, restricting the insertion of a new row when the SupplierId value of the inserted row does not match the ID column values of the Supplier's table.
Let me know if you have any further doubt
Simply because you don't insert shop_id and supplier_id values to the table, you should also insert these values as well.
Here:
INSERT INTO COFFEE (coffee_id,coffee_name,price_per_pound,shop_id,supplier_id)
VALUES ('15','espresso','15','45','25');
Related
I'm currently working on a mysql project for my class and I'm wondering if the PK-FK of a subclass table can be referenced as FK for another table instead of the PK of the parent class.
Let's say I have the subclass table employees written as:
CREATE TABLE employees (
Person_ID int PRIMARY KEY,
Designation varchar(50),
FOREIGN KEY (Person_ID) REFERENCES persons(Person_ID));
As for the parent class,
CREATE TABLE persons (
Person_ID int NOT NULL AUTO_INCREMENT,
Last_Name varchar(255),
Middle_Name varchar(255),
First_Name varchar(255),
PRIMARY KEY(Person_ID));
Let's say I want to create another table works whose FK references Person_ID from the subclass employees, not the parent class persons.
CREATE TABLE works (
project_ID PRIMARY KEY,
date_started date,
FOREIGN KEY (Person_ID) REFERENCES employees(Person_ID));
Thanks!
Yes, that's technically possible (I guess you tested that already) and is logically also OK in such a case as yours. In fact referencing persons would be wrong if, logically, only employees can take part in the "works on" relation -- the FK constraint wouldn't ensure that they're only employees.
It is no Problem, but you have always check if the id exist.
Ring connection can cause problems.
CREATE TABLE persons (
Person_ID int AUTO_INCREMENT,
Last_Name varchar(255),
Middle_Name varchar(255),
First_Name varchar(255),
PRIMARY KEY(Person_ID));
✓
CREATE TABLE employees (
Person_ID int PRIMARY KEY,
Designation varchar(50),
foreign key (Person_ID) REFERENCES persons(Person_ID));
✓
CREATE TABLE works (
project_ID Int PRIMARY KEY,
date_started date,
Person_ID int,
FOREIGN KEY (Person_ID) REFERENCES employees(Person_ID));
INSERT INTo persons VALUES (NULL,'A','B','C')
INSERT INTO employees VALUES (1,'test')
INSERT INTO works VALUES (1,NOW(),1)
db<>fiddle here
Is there a way to create a column in a table that derives its values from the average of the values of a column of another table.
I'd like to have the rating column in the table Series have the averages of the opinion column of the table Status where the name are the same.
This is the current database.
CREATE TABLE User
(UName VARCHAR(30),
Password VARCHAR(30) NOT NULL,
Score INT,
PRIMARY KEY(UName));```
CREATE TABLE Status
(UName VARCHAR(30),
SName VARCHAR(50),
Opinion INT,
CONSTRAINT OpinionCk CHECK (Opinion BETWEEN 0 AND 100),
PRIMARY KEY(UName, Sname),
FOREIGN KEY(UName) REFERENCES User(UName) ON UPDATE CASCADE ON DELETE CASCADE,
FOREIGN KEY (SName) REFERENCES Serie(SName) ON UPDATE CASCADE ON DELETE CASCADE);
/* here comes the part where i have the problem:*/
CREATE TABLE Series
(SName VARCHAR(50),
Rating REAL AS (
(SELECT AVG(Opinion)
FROM Status
WHERE
Status.SName = Series.SName)
),
Genre VARCHAR(50),
Episodecount INT,
PRIMARY KEY(SName));
Is there a better way to create the table Series? Maybe as a view...?
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
I have a sport club presence list on paper which I have to bring online.
Basically, I have everything in handle except the SQL schema architecture.
I have never designed a DataBase and I'm not sure if it's the right way. I appreciate any help!
If the person is present we make a x with a pen on paper :)
To do to look the same like on the paper but in an app I try to develop a Java Vaadin App with Spring Data JPA-Hibernate.
On paper and in the future APP look like this:
And this is the MySQL schema:
create table person(
id int PRIMARY KEY AUTO_INCREMENT,
first_name varchar(20)
);
create table isPresent(
id int PRIMARY KEY AUTO_INCREMENT,
isPresent boolean
);
create table persons_isPresent(
person_id int,
isPresent_id int,
FOREIGN KEY (person_id)
REFERENCES person(id),
FOREIGN KEY (isPresent_id)
REFERENCES isPresent(id)
);
create table training(
id int PRIMARY KEY AUTO_INCREMENT,
person_id int,
isPresent_id int,
training_time datetime,
FOREIGN KEY (person_id)
REFERENCES person(id),
FOREIGN KEY (isPresent_id)
REFERENCES isPresent(id)
);
I have never designed a DataBase and I'm not sure if it's the right way. I appreciate any help!
It seems unnecessary to have ispresent ID's.
I would keep your Person table as is.
Create a Training table with an ID and time, and an TrainingAttendance table with a Training ID and a Person ID. If you want to check a person's attendance at a training, check if a record exists in TrainingAttendance with the Person's ID and the Training ID.
CREATE TABLE PERSON (
PERSON_ID INTEGER NOT NULL PRIMARY KEY,
FIRST_NAME VARCHAR(20) NOT NULL);
CREATE TABLE TRAINING (
TRAINING_ID INTEGER NOT NULL PRIMARY KEY
TRAINING_TIME DATETIME NOT NULL);
CREATE TABLE TRAINING_ATTENDANCE (
TRAINING_ID INTEGER NOT NULL,
PERSON_ID INTEGER NOT NULL,
FOREIGN KEY(PERSON_ID) REFERENCES PERSON(PERSON_ID),
FOREIGN KEY(TRAINING_ID) REFERENCES TRAINING(TRAINING_ID),
PRIMARY KEY(TRAINING_ID, PERSON_ID));
I think it might be cleaner to think about training sessions independently. Then you could achieve that with three tables [training]<-[attendee]->[person], where the attendee is a binding table. So maybe something like this:
create table training(
id int PRIMARY KEY AUTO_INCREMENT,
training_time datetime
);
create table person(
id int PRIMARY KEY AUTO_INCREMENT,
first_name varchar(20)
);
create table attendee(
id int PRIMARY KEY AUTO_INCREMENT,
person_id int,
training_id int,
FOREIGN KEY (person_id) REFERENCES person(id),
FOREIGN KEY (training_id) REFERENCES training(id)
);
I tried it out with some simple inserts/select and it might do the trick for you?
insert INTO person (first_name) VALUES ('Pavel');
insert INTO training (training_time) VALUES (NOW());
insert INTO attendee (person_id, training_id) VALUES (1,1);
select person.first_name, training.training_time
from attendee, person, training
where person.id = attendee.person_id
AND training.id = attendee.training_id;
I am continuously getting this flag:
1452 - Cannot add or update a child row: a foreign key constraint fails (mydb4653.stars, CONSTRAINT fk_stars_movie FOREIGN KEY
(movieID) REFERENCES movie (id))
when I try to insert the data into the table
These are the tables
movie(id, title, relYear, category, runTime, director,
studioName, description, rating)
actor(aID, fName, surname, gender)
stars(movieID, actorID)
movGenre(movieID, genre)
I think it could have something to do with the fact that its not the only movieID as it is the only one I am having issues with. It is definitely indexed
I have tried:
CREATE TABLE stars
(movieID INTEGER,
actorID INTEGER NOT NULL PRIMARY KEY,
CONSTRAINT fk_stars_movie FOREIGN KEY (movieID) REFERENCES movie(ID)
);
as well as manually making it the foreign key in the relation view. It is also the same data type as its primary key so that's not the issue either.
CREATE TABLE movie
(id INTEGER NOT NULL PRIMARY KEY,
title VARCHAR(100),
relYear INTEGER,
category VARCHAR(5),
runTime INTEGER,
director VARCHAR(50),
studioName VARCHAR(100),
description VARCHAR(500),
rating DECIMAL(10,2)
);
set foreign_key_checks=0;
Your insert query goes here...
set foreign_key_checks=1;