I need to JOIN using a linking table - sql

The three tables are as follows:
CREATE TABLE Artist
(
ArtistKey char(20) NOT NULL PRIMARY KEY,
ArtistName varchar(50) NOT NULL
)
CREATE TABLE AlbumInfo
(
AlbumInfoKey char(20) NOT NULL PRIMARY KEY,
AlbumTitle varchar(50) NOT NULL,
AlbumDate date NULL,
AlbumStudio varchar(50) NULL
)
CREATE TABLE AlbumArtist
(
AlbumInfoKey char(20) NOT NULL,
ArtistKey char(20) NOT NULL,
PRIMARY KEY CLUSTERED
(
AlbumInfoKey ASC,
ArtistKey ASC
))
My objective is to list all of the artists and their albums. I can't seem to get anything to work.
I have tried:
SELECT
Artist.ArtistName,
AlbumInfo.AlbumTitle
FROM Artist
JOIN AlbumArtist
ON Artist.ArtistKey = AlbumArtist.ArtistKey
JOIN AlbumInfo
On AlbumInfo.AlbumInfoKey = AlbumArtist.AlbumInfoKey
However this gives me back nothing not even an error.

Alright, I had to re-do your whole task, and I have come up with more professional, and better way of managing database. You need to drop those tables, and re-do whole thing like show in code below :
--First create Artist table
CREATE TABLE Artist
(
Artist_key int PRIMARY KEY IDENTITY(1,1),
ArtistName varchar(50) NOT NULL,
);
--Then create Album table
CREATE TABLE AlbumInfo
(
Album_key int NOT NULL PRIMARY KEY IDENTITY(1,1),
AlbumTitle varchar(50) NOT NULL,
AlbumDate date NULL,
AlbumStudio varchar(50) NULL,
Artist_key int FOREIGN KEY (Artist_key) REFERENCES Artist(Artist_key)
);
-- Must have Artist data before referencing in the album table
INSERT into Artist (ArtistName) values ('John')
INSERT into AlbumInfo (AlbumTitle,AlbumDate,AlbumStudio,Artist_key) values ('ABC3','2020-6-12','Def3',(select Artist_key from Artist where Artist_key = 1 ))
--test if data has been inserted
SELECT * FROM Artist
SELECT * FROM AlbumInfo
-- And finally this query will show the Artist with their relevant Albums
SELECT ArtistName,af.AlbumTitle,AlbumStudio from Artist a join AlbumInfo af on af.Artist_key = a.Artist_key
And the result is :

Related

ALTER TABLE statement conflicted with the FOREIGN KEY constraint

When creating the foreign key I came across this error. Below is my code.
create table tblPerson(
ID int not null primary key,
Fullname varchar(50) not null,
Email varchar(50) not null,
GenderId int
)
create table tblGender (
ID int not null primary key,
Gender varchar(50) not null
)
alter table tblPerson add constraint tblPerson_GenderId_FK
foreign key (GenderId) references tblGender(ID)
You want to identify any "do not align" rows....
I have made the below.
You won't be able to add the FK constraint, if any rows come back from the SELECT query.
I have also removed the hungarian notation for "tbl". I would advise against it.
create table dbo.Person(
ID int not null primary key,
Fullname varchar(50) not null,
Email varchar(50) not null,
GenderId int )
create table dbo.Gender (
ID int not null primary key,
Gender varchar(50) not null
)
/* any rows below? your FK creation will fail */
Select *, p.GenderId as 'HoustonWeHaveAProblemValue' from dbo.Person p Where Not Exists (Select 1 from dbo.Gender g where g.ID = p.GenderId)
alter table dbo.Person add constraint Person_GenderId_FK
foreign key (GenderId) references dbo.Gender(ID)
Hi please use the following code to achieve your goal :
1-First create tblGender:
create table tblGender (
ID int not null primary key,
Gender varchar(50) not null
)
2-Then create table tblPerson with the relationship between 2 tables since the beginning:
create table tblPerson(
ID int not null primary key,
Fullname varchar(50) not null,
Email varchar(50) not null,
GenderId int references tblGender(ID)
)
works fine.

How do i fill my table with data from 3 different tables?

So I am working on a football world cup database. These are my important tables:
CREATE TABLE Countries(
Cid SERIAL PRIMARY KEY,
Name VARCHAR(256) NOT NULL UNIQUE
);
CREATE TABLE Stadiums(
Sid SERIAL PRIMARY KEY,
Name VARCHAR(256) NOT NULL UNIQUE,
Cid INT REFERENCES Countries NOT NULL
);
CREATE TABLE Groups(
Gid SERIAL PRIMARY KEY,
Name VARCHAR(64) NOT NULL,
TYear SMALLINT REFERENCES Tournaments NOT NULL
);
CREATE TABLE Teams(
Tid SERIAL PRIMARY KEY,
Cid INT REFERENCES Countries NOT NULL,
Gid INT REFERENCES Groups NOT NULL
);
CREATE TABLE Matches(
Mid INT PRIMARY KEY,
HomeTid INT REFERENCES Teams NOT NULL,
VisitTid INT REFERENCES Teams NOT NULL,
HomeScore SMALLINT NOT NULL,
VisitScore SMALLINT NOT NULL,
MatchDate DATE NOT NULL,
MatchType VARCHAR(64) NOT NULL,
Sid INT REFERENCES Stadiums NOT NULL
);
CREATE TABLE tempmatches(
year INTEGER,
host_country VARCHAR(255),
match_id INTEGER,
type VARCHAR(255),
date DATE,
location1 VARCHAR(255),
team1 VARCHAR(255),
team2 VARCHAR(255),
score1 INTEGER,
score2 INTEGER
);
so my current problem is that I need to populate the columns HomeTid and VisitId of the Matches table with the tid's from the team's table that corresponds with the country of that team from the countries table but I'm not sure how to do that. I tried a few queries but none of them seemed to work. Has anyone an idea on how to solve this?
Using JOIN keyword you can combine 2 tables data.
Here, in this case, you have to use 3-way join.
Eg:
3-way JOIN can be used in this way:
SELECT * FROM table1 JOIN table2 ON table1.col1=table2.col2 JOIN table3 ON table3.col3=table.col1;
Here the 2 tables will get joined based on the columns mentioned after the "ON" keyword.
Here is a reference link in which JOIN is explained clearly
https://www.w3schools.com/sql/sql_join.asp
Use JOIN operation. In SQL it helps to combine several tables(queries) in one

Address table applied to Users and Stores

On a database I have the following tables:
create table dbo.Stores (
Id int not null
Name nvarchar (120) not null
)
create table dbo.Users (
Id int not null
Name nvarchar (120) not null
)
Each User or Shop can have:
1 - One physical address;
2 - One website or social media addresses.
Should I have tables for Addresses and Social Media. For example:
create table dbo.Addresses (
Id int not null
Street nvarchar (120) not null,
PostalCode nvarchar (12) not null
City nvarchar (40) not null,
Latitude float null,
Longitude float null
)
create table dbo.UserAddresses (
UserId int not null,
AddressId int not null
)
And the same for Social Media, phone numbers and so on ...
Should I just add Columns to the Users table?
Update 1
For website addresses and social media addresses I am considering having the following:
create table dbo.UserWebAddresses (
UserId int not null,
WebAddressTypeId int not null,
Value nvarchar(200) not null
)
create table dbo.WebAddressTypes (
Id int not null,
Name nvarchar(20) not null
)
Does this make sense?
Add those columns directly to dbo.Stores and dbo.Users if there are no duplicated rows. If they might be duplicated, then create a new table and use FKs.
CREATE TABLE dbo.Stores
(
Id INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
Name NVARCHAR(120) NOT NULL,
Address_Id INT NULL
);
CREATE TABLE dbo.Users
(
Id INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
Name NVARCHAR(120) NOT NULL,
Address_Id INT NULL
);
CREATE TABLE dbo.Addresses
(
Id INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
Street NVARCHAR(120) NOT NULL,
PostalCode NVARCHAR(12) NOT NULL,
City NVARCHAR(40) NOT NULL,
Latitude FLOAT NULL,
Longitude FLOAT NULL
);
ALTER TABLE dbo.Stores
ADD CONSTRAINT Stores_Address_Id_FK FOREIGN KEY (Address_Id) REFERENCES dbo.Addresses(Id);
ALTER TABLE dbo.Users
ADD CONSTRAINT Users_Address_Id_FK FOREIGN KEY (Address_Id) REFERENCES dbo.Addresses(Id);
We can also go with the following solution as well if I understood everything correct:
CREATE TABLE dbo.Stores
(
Id INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
Name NVARCHAR(120) NOT NULL,
Address_Id INT NULL,
Latitude FLOAT NULL,
Longitude FLOAT NULL
);
CREATE TABLE dbo.Users
(
Id INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
Name NVARCHAR(120) NOT NULL,
Address_Id INT NULL,
Latitude FLOAT NULL,
Longitude FLOAT NULL
);
CREATE TABLE dbo.Addresses
(
Id INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
Street NVARCHAR(120) NOT NULL,
PostalCode NVARCHAR(12) NOT NULL,
City NVARCHAR(40) NOT NULL
);
ALTER TABLE dbo.Stores
ADD CONSTRAINT Stores_Address_Id_FK FOREIGN KEY (Address_Id) REFERENCES dbo.Addresses(Id);
ALTER TABLE dbo.Users
ADD CONSTRAINT Users_Address_Id_FK FOREIGN KEY (Address_Id) REFERENCES dbo.Addresses(Id);

SQL SELECT FROM TWO TABLES INNER JOIN

I am trying select from my Album and ArtistBand Table and display the Name and Bandname in alphabetical order. When in try to use the select statement below it shows up with all the albums on each band. Any help would be appreciated project for school.
CREATE TABLE ArtistBand
(
ArtistID INT AUTO_INCREMENT PRIMARY KEY,
BandName VARCHAR(255) NOT NULL,
NameOfMembers VARCHAR(255),
NumberOfMembers INT
);
CREATE TABLE Genre
(
GenreID INT AUTO_INCREMENT PRIMARY KEY,
GenreType VARCHAR(255) NOT NULL
);
CREATE TABLE Album
(
AlbumID INT AUTO_INCREMENT PRIMARY KEY,
Name VARCHAR (255) NOT NULL,
ReleaseDate DATE NOT NULL,
Producers VARCHAR (255),
ArtistID INT,
GenreID INT,
FOREIGN KEY(ArtistID) REFERENCES ArtistBand(ArtistID),
FOREIGN KEY (GenreID) REFERENCES Genre (GenreID)
);
CREATE TABLE LookUp
(
AlbumID INT,
GenreID INT,
FOREIGN KEY (AlbumID) REFERENCES Album (AlbumID),
FOREIGN KEY (GenreID) REFERENCES Genre (GenreID)
);
INSERT INTO ArtistBand
VALUES
(NULL,'ACDC','BrianJohnson',4),
(NULL,'Metallica','JamesHeitfield',4),
(NULL,'TheBeatles','JohnLennon',4),
(NULL,'JayZ','ShawnCarter',1),
(NULL,'DangerMouse','BrianBurton',1);
INSERT INTO Album
VALUES
(NULL,'BackInBlack','1980-01-01',NULL,NULL,NULL),
(NULL,'TheBlackAlbum','1991-01-01',NULL,NULL,NULL),
(NULL,'WhiteAlbum','1968-01-01',NULL,NULL,NULL),
(NULL,'TheBlackAlbum','2003-01-01',NULL,NULL,NULL),
(NULL,'TheGreyAlbum','2004-01-01',NULL,NULL,NULL);
INSERT INTO Genre
VALUES
(NULL,'HeavyMetal'),
(NULL,'HeavyMetal'),
(NULL,'Pop'),
(NULL,'HipHop'),
(NULL,'HipHop');
SELECT
ArtistBand.BandName, Album.Name
FROM
ArtistBand
JOIN
Album
ORDER BY
ArtistBand.BandName;
You need to add condition on your join, that the ArtistID should be the same in both tables. So your query will look like below:
SELECT ArtistBand.BandName, Album.Name
FROM ArtistBand
JOIN Album ON ArtistBand.ArtistID = Album.ArtistID
ORDER BY ArtistBand.BandName;

Movie booking: How to let every show have its own set of seats?

I have made a movie booking database in mysql workbench (6.2). This database is then connected to eclipse where I in java have programmed a GUI for the movie booking system.
Everything works well with the GUI/database but there is one logical problem:
If a reservation is made for a show, naturally, the number of seats left in that theater where that show is to be played, will be reduced by 1 for every reservation. But if there is a show that's on a different date but on the same theater then this theaters seats is also reduced by 1 which is wrong.
E.g. a show on Monday should have its own set of seats and one on Tuesday should have its own. A solution could be to create a new column 'nbrseats' in 'shows' but I want it to get its seats from Theaters if that's possible.
Database
set foreign_key_checks = 0;
drop table if exists Users;
drop table if exists Theaters;
drop table if exists Movies;
drop table if exists reservations;
drop table if exists Shows;
create table Theaters (
theatername char(11) not null,
NbrSeats char(20) not null,
primary key (theatername)
)engine innoDB;
create table Movies (
moviename char(30) not null,
primary key (moviename)
)engine innoDB;
create table Shows (
movieDate DATE not null,
theatername char(11) not null,
moviename char(30) not null,
id integer auto_increment,
foreign key (theatername) references Theaters(theatername),
foreign key (moviename) references Movies(moviename),
primary key (id)
)engine innoDB;
create table Users (
username char(20) not null,
fullname char(30) not null,
phonenbr char(10) not null,
address varchar(20) not null,
primary key (username)
) engine innoDB;
create table reservations (
resNbr integer auto_increment,
username char(20) not null,
showId int(30) not null,
foreign key(showid) references Shows(id),
foreign key (username) references Users(username),
primary key (resNbr)
)engine innoDB;
-- insert data into the tables
insert into Users values
('Temp1','Name Name', '0701231231', 'Street1');
insert into Movies values
('Star Wars'),
('Dallas'),
('Falcon Crest');
insert into Theaters values
('Filmstaden', '100'),
('SF', '129'),
('Royal', '120');
insert into Shows values
('20151203','Royal', 'Falcon Crest', null),
('20151003','SF', 'Dallas', null),
('20150803','Filmstaden', 'Star Wars', null);
Thanks!
Just make a new column to store the number of booked seats in the reservations table. Then you can write a query to calculate the number of free seats based on the reservations made and the seats available in this theater.
Example to get free seats of showid 1, with two reservations of 5 and 2 seats:
set foreign_key_checks = 0;
drop table if exists Users;
drop table if exists Theaters;
drop table if exists Movies;
drop table if exists reservations;
drop table if exists Shows;
create table Theaters (
theatername char(11) not null,
NbrSeats char(20) not null,
primary key (theatername)
)engine innoDB;
create table Movies (
moviename char(30) not null,
primary key (moviename)
)engine innoDB;
create table Shows (
movieDate DATE not null,
theatername char(11) not null,
moviename char(30) not null,
id integer auto_increment,
foreign key (theatername) references Theaters(theatername),
foreign key (moviename) references Movies(moviename),
primary key (id)
)engine innoDB;
create table Users (
username char(20) not null,
fullname char(30) not null,
phonenbr char(10) not null,
address varchar(20) not null,
primary key (username)
) engine innoDB;
create table reservations (
resNbr integer auto_increment,
username char(20) not null,
showId int(30) not null,
seats int not null,
foreign key(showid) references Shows(id),
foreign key (username) references Users(username),
primary key (resNbr)
)engine innoDB;
-- insert data into the tables
insert into Users values
('Temp1','Name Name', '0701231231', 'Street1');
insert into Movies values
('Star Wars'),
('Dallas'),
('Falcon Crest');
insert into Theaters values
('Filmstaden', '100'),
('SF', '129'),
('Royal', '120');
insert into Shows values
('20151203','Royal', 'Falcon Crest', null),
('20151003','SF', 'Dallas', null),
('20150803','Filmstaden', 'Star Wars', null);
insert into reservations values
(null,'Temp1', 1, 5),
(null,'Temp1', 1, 2),
(null,'Temp1', 2, 3);
select
Shows.id,
Shows.theatername,
Theaters.NbrSeats,
sum(reservations.seats),
Theaters.NbrSeats-sum(reservations.seats) freeseats
from Shows
left join Theaters
on Shows.theatername = Theaters.theatername
left join reservations
on Shows.id = reservations.showId
where Shows.id = 1
group by
Shows.id,
Shows.theatername,
Theaters.NbrSeats
Database is correct, it was a matter of querying
here is an (somewhat primitive) example query for id = 2:
select nbrseats - (select count(showId) from reservations
where showId = (select id from shows where id = 2)) from theaters
where theatername = (select theatername from shows where id = 2);