Beginner learning sql joins in mySQL - sql

I have created 3 tables: dog, customer and owner. It is a many to one relationship with many dogs owned by 1 customer.
CREATE TABLE dog
(
DogID int(6) NOT NULL,
DogName varchar(15),
medicalID int (6),
Gender character(1) check(gender in ('m', 'f')),
Age int(2),
Breed varchar(15),
size character (1) check(size in ('s', 'm', 'l')),
primary key (DogID));
CREATE TABLE Owns
(
DogID int (6)primary key,
CustomerID int (6),
foreign key (CustomerID) references customer (CustomerID),
foreign key (DogID) references dog (DogID));
CREATE TABLE customer
(
CustomerID int(6) NOT NULL,
FirstName varchar(15),
Surname varchar(15),
Address varchar(225),
email varchar (30),
TelNo varchar (15),
MobNo Varchar (15),
EmergencyName varchar (40),
EmergencyPhoneNo varchar(15),
primary key (CustomerID));
I have queried with but nothing is returned.
select dog.dogName
from dog, owns, customer
where owns.dogID = dog.dogId
and customer.customerID = owns.customerID
and customer.FirstName = "CustomersName";

You created the tables, now you need to INSERT the data.
INSERT INTO dog(<fields>) VALUES(<values>);

If you have successfully created the tables the next step is to put some data in them. Otherwise you won't get anything back from your query. You need to insert a record into the dog and customer tables and associate them via the owns table. After performing those 3 inserts you should be able to join on their keys and query for data.
For example:
insert into dog(DogID, DogName, medicalID, Gender, Age, Breed, Size) values ('111111', 'Spike', '111111', '12', 'Wolf', 'l' );
insert into customer ( CustomerID, FirstName, Surname, Address, email, TelNo, MobNo, EmergencyName, EmergencyPhoneNo ) values ( '222222', 'Abe', 'Lincoln', '123 Street', 'blah#blah.com', '8675309', '8675309', 'Bob', '8675309' );
insert into owns ( DogID, CustomerID ) values ( '111111', '222222' );
select DogName from dog as d
join owns as o on o.DogID = d.DogID
join customer as c on c.CustomerId = o.CustomerID
where c.FirstName = 'Abe';
Note that your syntax may be slightly different. I've been using Oracle for a while.

Related

Getting duplicate data when using the select statements

I'm getting duplicate data when trying to use the select statements, I have 9 rooms but I'm getting around 50-70 rooms when trying to display them. Help please?
I'm trying to insert data and display it using the select statement.
create table gym (
GymName VARCHAR(200) primary key,
openTime time not null,
closeTime time not null,
Price decimal not null,
);
create table Spa (
spaName VARCHAR(200) primary key,
openTime time not null,
closeTime time not null,
Price decimal not null,
);
create table customer (
CustomerID int primary key,
Firstname varchar(200) not null,
LastName varchar(200) not null,
DOB date not null check (DATEDIFF(year,DOB,getdate ()) > 18) ,
Gender char(4) not null check(Gender ='M' or Gender = 'F'),
Address varchar(200) not null default 'Jordan',
spaName VARCHAR(200) foreign key references Spa(spaName),
GymName VARCHAR(200) foreign key references gym(GymName),
);
Create table CustomerPhoNo (
CustomerID int foreign key references customer(CustomerID),
PhoneNo bigint not null,
);
create table Room (
roomNo int primary key,
Availability char(4) not null,
NoOfBeds int not null,
Rate int not null,
CheckIn date,
CheckOut date,
Price Decimal not null,
Breakfast char(4),
CustomerID int foreign key references customer(CustomerID),
);
create table LocationOfRoom (
roomNo int foreign key references Room(roomNo),
seaview char(4),
Location varchar(20) not null,
);
create table RoomType (
roomNo int foreign key references Room(roomNo),
familyRoom char(4),
doubleRoom char(4),
singleRoom char(4),
);
create table Gservice (
GymName VARCHAR(200) foreign key references gym(GymName),
Service VARCHAR(500) not null,
MachineType VARCHAR(500) not null,
);
create table PaymentCard (
CardID int primary key,
issueDate date not null,
Expirydate date not null,
CustomerID int foreign key references customer(CustomerID),
);
insert into customer values (325,'Mohammad','Alasharan','06-04-1984','M','Amman', 'BeautySpa', 'StrongBody')
insert into customer values (348,'John','Shelby','10-18-1998','M','Birmingham', 'LushLife', 'SilverGym')
insert into customer values (495,'Thomas','Hoffman','04-26-1968','M','Johannesburg', 'RelaxationTherapy', 'SilverGym')
insert into customer values (194,'Anne','Frank','07-22-2001','F','Frankfurt', 'BeautySpa', 'StrongBody')
insert into customer values (628,'Katie','Swan','02-10-1997','F','New South Wales', 'LushLife', 'FitnessHeroes')
insert into customer values (246,'Mahmoud','Alkutaifan','04-21-1994','M','Amman', 'BeautySpa', 'FitnessHeroes')
insert into customer values (864,'Karl-Heinz','Rummenigge','09-25-1955','M','Lippstadt', 'RelaxationTherapy', 'FitnessHeroes')
insert into customer values (824,'Dennis','Law','09-21-1979','M','london', 'RelaxationTherapy', 'FitnessHeroes')
insert into customer values (463,'Carles','Puyol','06-17-1973','M','madrid', 'LushLife', 'FitnessHeroes')
insert into Room values (124,'yes','1','4',null,null,'30','yes',null)
insert into Room values (135,'no','2','5','05-06-2022','05-09-2022','55','yes',495)
insert into Room values (121,'yes','1','3',null,null,'40','yes',null)
insert into Room values (139,'no','3','4','05-10-2022','05-14-2022','110','no',194)
insert into Room values (131,'no','3','3','05-18-2022','05-22-2022','130','yes',348)
insert into Room values (136,'no','4','4','04-14-2022','04-24-2022','120','yes',194)
insert into Room values (179,'yes','4','5',null,null,'95','no',null)
insert into Room values (138,'no','3','3','04-02-2022','04-06-2022','75','no',246)
insert into Room values (146,'no','3','5','05-10-2022','05-14-2022','80','yes',864)
insert into LocationOfRoom values (124,'no','south')
insert into LocationOfRoom values (135,'yes','north')
insert into LocationOfRoom values (121,'yes','south')
insert into LocationOfRoom values (139,'no','north')
insert into LocationOfRoom values (131,'no','East')
insert into LocationOfRoom values (136,'yes','west')
insert into LocationOfRoom values (179,'no','south')
insert into LocationOfRoom values (138,'no','west')
insert into LocationOfRoom values (146,'yes','north')
insert into RoomType values (124,'no','no','yes')
insert into RoomType values (135,'no','yes','no')
insert into RoomType values (121,'yes','no','no')
insert into RoomType values (139,'no','no','yes')
insert into RoomType values (131,'no','no','yes')
insert into RoomType values (136,'no','no','yes')
insert into RoomType values (179,'no','no','yes')
insert into RoomType values (138,'no','yes','no')
insert into RoomType values (146,'no','no','yes')
-- display Total number of customers who booked a single room with sea view option
select count(Firstname)
from LocationOfRoom, customer, RoomType, Room
where seaview='yes' and singleRoom='yes'
Any help would be greatly appreciated, thank you in advance!
Your FROM clause is missing the join condition for each table. In other words you are getting the cartesian product (every combination of rows) of the tables. Even distinct won't help (it will get the wrong answer). Use join conditions to link the keys of each table to each other. I'll leave this an exercise for you to try out, but this should be enough information to help you out.
I believe the solution for your problem is that you need to use DISTINCT:
SELECT COUNT(DISTINCT(Firstname))
FROM LocationOfRoom, customer, RoomType, Room
WHERE seaview='yes' AND singleRoom='yes'
I have tested it and it retrieves 9 Rooms.

error 1452 when trying to paste in values

when i try enter the last part of code i get the error message "error code : 1452 cannot add or update a child row a foreign key constraint fails"
CREATE TABLE products (
id int auto_increment primary key,
name varchar (30),
price decimal(3,2),
coffee_origin varchar (30)
);
CREATE TABLE customers (
id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(30),
last_name VARCHAR (30),
gender ENUM ('M','F'),
phone_number VARCHAR(11)
);
CREATE TABLE orders(
id INT AUTO_INCREMENT PRIMARY KEY,
product_id INT,
customer_id INT,
order_time DATETIME,
FOREIGN KEY (product_id) REFERENCES products(id),
FOREIGN KEY (customer_id) REFERENCES customers(id)
);
INSERT INTO orders (product_id,customer_id,order_time) VALUES (1,1,'2017-01-01 08-02-11');
In order to be able to insert your values into the orders table, I think you might need to add rows to your products and customers tables.
Here are possible examples of how you could add rows to your products and customers tables:
insert into products (name, price, coffee_origin) values ('Dark Blend', 4.99, 'Brazil');
insert into customers (first_name, last_name, gender, phone_number) values ('First Name', 'Last Name', 'M', '123-456-7890');
Then, you can find the id values that you might need to use for your final insert action by running the following queries:
select id from products where name = 'Dark Blend';
select id from customers where phone_number = '123-456-7890';
Finally, you can try running your insert action again, but this time using the id values from the queries above this; maybe like this, if you get back 1 for the ids of each of those queries above:
insert into orders (product_id, customer_id, order_time) values (1, 1, '2021-01-01 00:00:00');

Foreign key references invalid column error in MS SQL

This is all in MS SQL.
I've seen this issue pop up a lot, and I searched around but I still can't figure out my issue. I'm getting the error telling me my foreign key references in invalid column in an uncreated table. However, I created the table as it shows up on my database table list, so it shows it is created.
I tried to move that said table above the table that references it, yet I'm still receiving the error. Would anyone know how to fix this?
My code:
CREATE SCHEMA usr_in;
go
CREATE TABLE gender_interst (
id int IDENTITY (1,1),
gend_id int
CONSTRAINT gender_interstpk PRIMARY KEY (id)
)
CREATE TABLE gender (
id int IDENTITY (1,1),
gend VARCHAR (20)
CONSTRAINT genderpk PRIMARY KEY (id)
);
SELECT * FROM gender_interst LEFT JOIN gender on gender_interst.id = gender.id;
SELECT * from gender_interst;
CREATE TABLE user_info (
id int PRIMARY KEY IDENTITY (1,1),
usr_name VARCHAR (30) NOT NULL,
f_name VARCHAR (30) NOT NULL,
l_name VARCHAR (30),
b_day DATE,
email VARCHAR (120) NOT NULL,
genderpkid VARCHAR (10) NOT NULL,
CONSTRAINT gender_fk FOREIGN KEY (genderpkid) REFERENCES gender (genderpk),
);
INSERT
INTO user_info
( usr_name, f_name, l_name, b_day, genderpkid, email)
VALUES
('JMAN', 'JOHN', 'DOE', '1990-01-01','M','EX#EMAIL'),
('JAM','JANE', 'DOE', '1995-05-02','F','EX#EMAIL'),
('NMAN','NICK', 'WEBB', '1999-06-22','M','EX#EMAIL'),
('LOBA','LOLA', 'LILLY', '1994-01-08','F','EX#EMAIL'),
('NOTSPMAN','PETER', 'PARKER','1985-11-25','M','EX#EMAIL');
SELECT * FROM user_info;
Your foreign key needs to reference the name of a table column (which is either id or gend) and not the name of the primary key (genderpk).
Therefore the foreign key script (CONSTRAINT gender_fk FOREIGN KEY (genderpkid) REFERENCES gender (genderpk)) should look something like CONSTRAINT gender_fk FOREIGN KEY (genderpkid) REFERENCES gender (id)
However to create the relationship the two columns need to have the same data type. user_info .genderpkid is VARCHAR (10) and user_info.id is int.
The other problem you might encounter is that the insert scripts insert the data into genderpkid column as M or F. Therefore int is not going to work
If you were to use use the values M or F for gender, then you can create a script like:
CREATE TABLE gender (
id VARCHAR (1),
gender VARCHAR (20)
CONSTRAINT gender_pk PRIMARY KEY (id)
);
CREATE TABLE user_info (
id int PRIMARY KEY IDENTITY (1,1),
usr_name VARCHAR (30) NOT NULL,
f_name VARCHAR (30) NOT NULL,
l_name VARCHAR (30),
b_day DATE,
email VARCHAR (120) NOT NULL,
genderId VARCHAR (1) NOT NULL,
CONSTRAINT gender_fk FOREIGN KEY (genderId) REFERENCES gender (id),
);
INSERT INTO gender (id, gender)
VALUES
('F', 'Female'),
('M', 'Male')
INSERT
INTO user_info
( usr_name, f_name, l_name, b_day, genderId, email)
VALUES
('JMAN', 'JOHN', 'DOE', '1990-01-01','M','EX#EMAIL'),
('JAM','JANE', 'DOE', '1995-05-02','F','EX#EMAIL'),
('NMAN','NICK', 'WEBB', '1999-06-22','M','EX#EMAIL'),
('LOBA','LOLA', 'LILLY', '1994-01-08','F','EX#EMAIL'),
('NOTSPMAN','PETER', 'PARKER','1985-11-25','M','EX#EMAIL');
SELECT * FROM user_info;
A better approach could be, to pass the whole phraze (male / female) to the table user_info. The table gender can be used to enforce referential integrity. All your information is then contained in SELECT * FROM user_info
For example:
CREATE TABLE gender (
[name] VARCHAR (20)
CONSTRAINT gender_pk PRIMARY KEY ([name])
);
CREATE TABLE user_info (
id int PRIMARY KEY IDENTITY (1,1),
usr_name VARCHAR (30) NOT NULL,
f_name VARCHAR (30) NOT NULL,
l_name VARCHAR (30),
b_day DATE,
email VARCHAR (120) NOT NULL,
gender VARCHAR (20) NOT NULL,
genderIntrest VARCHAR (20) NOT NULL,
CONSTRAINT gender_fk FOREIGN KEY (gender) REFERENCES gender ([name]),
CONSTRAINT genderIntrest_fk FOREIGN KEY (genderIntrest) REFERENCES gender ([name]),
);
INSERT INTO gender ([name])
VALUES
('Female'),
('Male')
INSERT
INTO user_info
( usr_name, f_name, l_name, b_day, gender, genderIntrest, email)
VALUES
('JMAN', 'JOHN', 'DOE', '1990-01-01','Male','Female', 'EX#EMAIL'),
('JAM','JANE', 'DOE', '1995-05-02','Female','Female', 'EX#EMAIL'),
('NMAN','NICK', 'WEBB', '1999-06-22','Male','Female','EX#EMAIL'),
('LOBA','LOLA', 'LILLY', '1994-01-08','Female','Female','EX#EMAIL'),
('NOTSPMAN','PETER', 'PARKER','1985-11-25','Male','Female','EX#EMAIL');
SELECT * FROM user_info;
You can remove the gender table and let the app that consumes it pass in the data. However for a learning exercises, it's probably better to leave it in

Counting in Oracle 11g

all day I am struggling with oracle exrcises and again I stuck. I need to select last names of boxers with their wins of each weight category.
So I have:
table "boxer" with columns: id, fname, lname, weight
table "fight" with two foreign keys from table boxer (id_boxer1 and id_boxer2) and with one column winner (if boxer1 won then winner will be number 1, if boxer2 won then winner will be number 2)
table "category_weight" with columns: id, min_weight, max_weight, name (of a category)
Example:
CREATE TABLE category_weight(
id INTEGER NOT NULL,
min_weight SMALLINT NOT NULL,
max_weight SMALLINT NOT NULL,
name VARCHAR2(20) NOT NULL
);
ALTER TABLE category_weight ADD CONSTRAINT category_weight_pk PRIMARY KEY ( id );
CREATE TABLE boxer(
id INTEGER NOT NULL,
fname VARCHAR2(20) NOT NULL,
lname VARCHAR2(20) NOT NULL,
weight INTEGER NOT NULL
);
ALTER TABLE boxer ADD CONSTRAINT boxer_pk PRIMARY KEY ( id );
CREATE TABLE fight(
id INTEGER NOT NULL,
winner SMALLINT NOT NULL,
id_category_weight INTEGER NOT NULL,
id_boxer1 INTEGER NOT NULL,
id_boxer2 INTEGER NOT NULL
);
ALTER TABLE fight ADD CONSTRAINT fight_pk PRIMARY KEY ( id );
ALTER TABLE fight
ADD CONSTRAINT boxer_fk FOREIGN KEY ( id_boxer1 )
REFERENCES boxer ( id );
ALTER TABLE fight
ADD CONSTRAINT boxer_fk2 FOREIGN KEY ( id_boxer2 )
REFERENCES boxer ( id );
ALTER TABLE fight
ADD CONSTRAINT categ_weight_fk FOREIGN KEY ( id_category_weight )
REFERENCES category_weight ( id );
INSERT INTO boxer
VALUES ('1', 'Johnny','Johnny','60');
INSERT INTO boxer
VALUES ('2', 'Anthonny','Anthonny','54');
INSERT INTO boxer
VALUES ('3', 'Anonimm','Anonimm','59');
INSERT INTO boxer
VALUES ('4', 'John','Johnowski','71');
INSERT INTO category_weight
VALUES ('1', '1','70','category1');
INSERT INTO category_weight
VALUES ('2', '71','100','category2');
INSERT INTO fight
VALUES ('1','1','1','1','2');
INSERT INTO fight
VALUES ('2','2','1','3','1');
Boxer with ID "1" won two fights in category1, so the result should be:
Lname Category Wins
Johnny category1 2
Here, try this:
SELECT b.lname,
cw.max_weight AS WEIGHT_CLASS,
COUNT(CASE WHEN f.winner = b.id THEN 1 ELSE NULL END) AS WINS
FROM boxer b
INNER JOIN fight f ON b.id = f.id_boxer1 OR b.id = f.id_boxer2
INNER JOIN category_weight cw ON f.id_category_weight = cw.id
GROUP BY b.lname, cw.max_weight

Insert row into a table with foreign key

I have created two tables (SupplierName and SupplierAddress) in the address_book database.
Table SupplierName has one row inserted as shown in the insert statement below. I am struggling how to insert data into the table called SupplierAddress.
Please note that the SupplierID (primary key) from the SupplierName table is the foreign key in the SupplierAddress table. If my table design is incorrect please opine on that as well. I am just trying to create a simple database to learn SQL.
CREATE TABLE SupplierName
(
SupplierID int Primary Key identity(1,1) NOT NULL,
CompanyName varchar(50) NOT NULL,
EIN char(9) NOT NULL UNIQUE
)
CREATE TABLE SupplierAddress
(
ID int PRIMARY KEY IDENTITY(1,1) NOT NULL,
Address varchar(50),
City varchar(50),
State char(2),
ZipCode char(5),
Phone varchar(10),
SupplierAddressID int FOREIGN KEY REFERENCES SupplierName(SupplierID)
)
INSERT INTO SupplierName (CompanyName, EIN)
VALUES ('Clarks Electronics, Inc.', '123456789');
INSERT INTO SupplierAddress (Address, City, State, ZipCode, Phone)
VALUES ('2020 Garnet Road', 'York', 'PA', '17403', '717-123-4567')
SELECT
SupplierName.SupplierID, SupplierAddress.SupplierAddressID
FROM
SupplierName
INNER JOIN
SupplierAddress ON SupplierAddressID=SupplierID
Remove the hyphens from the phone number, or create table with more characters in phone
Look at http://www.dpriver.com/pp/sqlformat.htm to pretty format the sql
CREATE TABLE supplieraddress
(
id INT PRIMARY KEY IDENTITY(1, 1) NOT NULL,
address VARCHAR(50),
city VARCHAR(50),
state CHAR(2),
zipcode CHAR(5),
phone VARCHAR(10), -- make this longer
supplieraddressid INT FOREIGN KEY REFERENCES suppliername(supplierid)
)
INSERT INTO supplieraddress
(address,
city,
state,
zipcode,
phone)
-- add supplieraddressid and its value so that the FK is created
VALUES ('2020 Garnet Road',
'York',
'PA',
'17403',
'717-123-4567') -- or remove hyphens
SELECT suppliername.supplierid,
supplieraddress.supplieraddressid
FROM suppliername
INNER JOIN supplieraddress
ON supplieraddressid = supplierid