Print multiple rows in some order as different columns - sql

/* Note: on update/delete, no action (restriction) is
the default. (SQL Server & Oracle) */
CREATE TABLE Faculty (
FacNo CHAR(11) NOT NULL,
FacFirstName VARCHAR(30) NOT NULL,
FacLastName VARCHAR(30) NOT NULL,
FacCity VARCHAR(30) NOT NULL,
FacState CHAR(2) NOT NULL,
FacDept CHAR(6) NULL,
FacRank CHAR(4) NULL,
FacSalary DECIMAL(10,2) NULL,
FacSupervisor CHAR(11) NULL,
FacHireDate DATETIME NULL,
FacZipCode CHAR(10) NOT NULL,
CONSTRAINT FacultyPK PRIMARY KEY (FacNo),
CONSTRAINT SupervisorFK FOREIGN KEY (FacSupervisor) REFERENCES Faculty )
go
/* Note: on update cascade for FacSupervisor caused the following error
in SQL Server 2004:
Introducing FOREIGN KEY CONSTRAINT 'SupervisorFK' on table 'Faculty'
may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION
or ON UPDATE NO ACTION, or modify other FOREIGN KEY CONSTRAINTs.
*/
CREATE TABLE Course (
CourseNo CHAR(6) NOT NULL,
CrsDesc VARCHAR(50) NOT NULL,
CrsUnits INTEGER NULL,
CONSTRAINT CoursePK PRIMARY KEY (CourseNo) )
go
CREATE TABLE Offering (
OfferNo INTEGER NOT NULL,
CourseNo CHAR(6) NOT NULL,
OffTerm CHAR(6) NOT NULL,
OffYear INTEGER NOT NULL,
OffLocation VARCHAR(30) NULL,
OffTime VARCHAR(10) NULL,
FacNo CHAR(11) NULL,
OffDays CHAR(4) NULL,
CONSTRAINT OfferingPK PRIMARY KEY (OfferNo),
CONSTRAINT CourseFK FOREIGN KEY (CourseNo) REFERENCES Course,
CONSTRAINT FacultyFK FOREIGN KEY (FacNo) REFERENCES Faculty )
go
CREATE TABLE Student (
StdNo CHAR(11) NOT NULL,
StdFirstName VARCHAR(30) NOT NULL,
StdLastName VARCHAR(30) NOT NULL,
StdCity VARCHAR(30) NOT NULL,
StdState CHAR(2) NOT NULL,
StdZip CHAR(10) NOT NULL,
StdMajor CHAR(6) NULL,
StdClass CHAR(2) NULL,
StdGPA DECIMAL(3,2) NULL,
CONSTRAINT StudentPk PRIMARY KEY (StdNo) )
go
CREATE TABLE Enrollment (
OfferNo INTEGER NOT NULL,
StdNo CHAR(11) NOT NULL,
EnrGrade DECIMAL(3,2) NULL,
CONSTRAINT EnrollmentPK PRIMARY KEY (OfferNo, StdNo),
CONSTRAINT OfferingFK FOREIGN KEY (OfferNo) REFERENCES Offering
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT StudentFK FOREIGN KEY (StdNo) REFERENCES Student
ON DELETE CASCADE
ON UPDATE CASCADE )
go
INSERT INTO Faculty
VALUES ('543210987','VICTORIA','EMMANUEL','BOTHELL','WA','MS','PROF',120000.00,NULL,'4/15/2005','98011-2242')
go
INSERT INTO Faculty
VALUES ('765432109','NICKI','MACON','BELLEVUE','WA','FIN','PROF',65000.00,NULL,'4/11/2006','98015-9945')
go
INSERT INTO Faculty
VALUES ('654321098','LEONARD','FIBON','SEATTLE','WA','MS','ASSC',70000.00,'543210987','5/1/2003','98121-0094')
go
INSERT INTO Faculty
VALUES ('098765432','LEONARD','VINCE','SEATTLE','WA','MS','ASST',35000.00,'654321098','4/10/2004','98111-9921')
go
INSERT INTO Faculty
VALUES ('876543210','CRISTOPHER','COLAN','SEATTLE','WA','MS','ASST',40000.00,'654321098','3/1/2008','98114-1332')
go
INSERT INTO Faculty
VALUES ('987654321','JULIA','MILLS','SEATTLE','WA','FIN','ASSC',75000.00,'765432109','3/15/2009','98114-9954')
go
INSERT INTO Course
VALUES ('FIN300','FUNDAMENTALS OF FINANCE',4)
go
INSERT INTO Course
VALUES ('FIN450','PRINCIPLES OF INVESTMENTS',4)
go
INSERT INTO Course
VALUES ('FIN480','CORPORATE FINANCE',4)
go
INSERT INTO Course
VALUES ('IS320','FUNDAMENTALS OF BUSINESS PROGRAMMING',4)
go
INSERT INTO Course
VALUES ('IS460','SYSTEMS ANALYSIS',4)
go
INSERT INTO Course
VALUES ('IS470','BUSINESS DATA COMMUNICATIONS',4)
go
INSERT INTO Course
VALUES ('IS480','FUNDAMENTALS OF DATABASE MANAGEMENT',4)
go
INSERT INTO Offering
VALUES (1111,'IS320','SUMMER',2017,'BLM302','10:30:00',NULL,'MW')
go
INSERT INTO Offering
VALUES (1234,'IS320','FALL',2016,'BLM302','10:30:00','098765432','MW')
go
INSERT INTO Offering
VALUES (2222,'IS460','SUMMER',2016,'BLM412','13:30:00',NULL,'TTH')
go
INSERT INTO Offering
VALUES (3333,'IS320','SPRING',2017,'BLM214','8:30:00','098765432','MW')
go
INSERT INTO Offering
VALUES (4321,'IS320','FALL',2016,'BLM214','15:30:00','098765432','TTH')
go
INSERT INTO Offering
VALUES (4444,'IS320','WINTER',2017,'BLM302','15:30:00','543210987','TTH')
go
INSERT INTO Offering
VALUES (5555,'FIN300','WINTER',2017,'BLM207','8:30:00','765432109','MW')
go
INSERT INTO Offering
VALUES (5678,'IS480','WINTER',2017,'BLM302','10:30:00','987654321','MW')
go
INSERT INTO Offering
VALUES (5679,'IS480','SPRING',2017,'BLM412','15:30:00','876543210','TTH')
go
INSERT INTO Offering
VALUES (6666,'FIN450','WINTER',2017,'BLM212','10:30:00','987654321','TTH')
go
INSERT INTO Offering
VALUES (7777,'FIN480','SPRING',2017,'BLM305','13:30:00','765432109','MW')
go
INSERT INTO Offering
VALUES (8888,'IS320','SUMMER',2017,'BLM405','13:30:00','654321098','MW')
go
INSERT INTO Offering
VALUES (9876,'IS460','SPRING',2017,'BLM307','13:30:00','654321098','TTH')
go
INSERT INTO Student
VALUES ('123456789','HOMER','WELLS','SEATTLE','WA','98121-1111','IS','FR',3.00)
go
INSERT INTO Student
VALUES ('124567890','BOB','NORBERT','BOTHELL','WA','98011-2121','FIN','JR',2.70)
go
INSERT INTO Student
VALUES ('234567890','CANDY','KENDALL','TACOMA','WA','99042-3321','ACCT','JR',3.50)
go
INSERT INTO Student
VALUES ('345678901','WALLY','KENDALL','SEATTLE','WA','98123-1141','IS','SR',2.80)
go
INSERT INTO Student
VALUES ('456789012','JOE','ESTRADA','SEATTLE','WA','98121-2333','FIN','SR',3.20)
go
INSERT INTO Student
VALUES ('567890123','MARIAH','DODGE','SEATTLE','WA','98114-0021','IS','JR',3.60)
go
INSERT INTO Student
VALUES ('678901234','TESS','DODGE','REDMOND','WA','98116-2344','ACCT','SO',3.30)
go
INSERT INTO Student
VALUES ('789012345','ROBERTO','MORALES','SEATTLE','WA','98121-2212','FIN','JR',2.50)
go
INSERT INTO Student
VALUES ('876543210','CRISTOPHER','COLAN','SEATTLE','WA','98114-1332','IS','SR',4.00)
go
INSERT INTO Student
VALUES ('890123456','LUKE','BRAZZI','SEATTLE','WA','98116-0021','IS','SR',2.20)
go
INSERT INTO Student
VALUES ('901234567','WILLIAM','PILGRIM','BOTHELL','WA','98113-1885','IS','SO',3.80)
go
INSERT INTO Enrollment
VALUES (1234,'123456789',3.30)
go
INSERT INTO Enrollment
VALUES (1234,'234567890',3.50)
go
INSERT INTO Enrollment
VALUES (1234,'345678901',3.20)
go
INSERT INTO Enrollment
VALUES (1234,'456789012',3.10)
go
INSERT INTO Enrollment
VALUES (1234,'567890123',3.80)
go
INSERT INTO Enrollment
VALUES (1234,'678901234',3.40)
go
INSERT INTO Enrollment
VALUES (4321,'123456789',3.50)
go
INSERT INTO Enrollment
VALUES (4321,'124567890',3.20)
go
INSERT INTO Enrollment
VALUES (4321,'789012345',3.50)
go
INSERT INTO Enrollment
VALUES (4321,'876543210',3.10)
go
INSERT INTO Enrollment
VALUES (4321,'890123456',3.40)
go
INSERT INTO Enrollment
VALUES (4321,'901234567',3.10)
go
INSERT INTO Enrollment
VALUES (5555,'123456789',3.20)
go
INSERT INTO Enrollment
VALUES (5555,'124567890',2.70)
go
INSERT INTO Enrollment
VALUES (5678,'123456789',3.20)
go
INSERT INTO Enrollment
VALUES (5678,'234567890',2.80)
go
INSERT INTO Enrollment
VALUES (5678,'345678901',3.30)
go
INSERT INTO Enrollment
VALUES (5678,'456789012',3.40)
go
INSERT INTO Enrollment
VALUES (5678,'567890123',2.60)
go
INSERT INTO Enrollment
VALUES (5679,'123456789',2.00)
go
INSERT INTO Enrollment
VALUES (5679,'124567890',3.70)
go
INSERT INTO Enrollment
VALUES (5679,'678901234',3.30)
go
INSERT INTO Enrollment
VALUES (5679,'789012345',3.80)
go
INSERT INTO Enrollment
VALUES (5679,'890123456',2.90)
go
INSERT INTO Enrollment
VALUES (5679,'901234567',3.10)
go
INSERT INTO Enrollment
VALUES (6666,'234567890',3.10)
go
INSERT INTO Enrollment
VALUES (6666,'567890123',3.60)
go
INSERT INTO Enrollment
VALUES (7777,'876543210',3.40)
go
INSERT INTO Enrollment
VALUES (7777,'890123456',3.70)
go
INSERT INTO Enrollment
VALUES (7777,'901234567',3.40)
go
INSERT INTO Enrollment
VALUES (9876,'124567890',3.50)
go
INSERT INTO Enrollment
VALUES (9876,'234567890',3.20)
go
INSERT INTO Enrollment
VALUES (9876,'345678901',3.20)
go
INSERT INTO Enrollment
VALUES (9876,'456789012',3.40)
go
INSERT INTO Enrollment
VALUES (9876,'567890123',2.60)
go
INSERT INTO Enrollment
VALUES (9876,'678901234',3.30)
go
INSERT INTO Enrollment
VALUES (9876,'901234567',4.00)
go
Schema for example.
Get all the faculty numbers (FacNo) and last names (FacLastName) of two different faculty who offered courses in the same offering year (OffYear). There must be no duplicates in the output.
*Note: For instance, if both P1 Smith and P2 Peters offered courses in 2021, then [P1, Smith, P2, Peters] (or [P2, Peters, P1, Smith], but not both) must be selected. So, the output must look like this:
FacNo FacLastName FacNo FacLastName
===== =========== ===== ===========
P1 Smith P2 Peters
... ... ... ...
===== =========== ===== ===========*
I am trying to do something like this and I can't even think where to start? How do I approach this problem?
I tried something like this
SELECT f1.FacNo, f1.FacLastName
FROM Offering o1
INNER JOIN Faculty f1 on o1.FacNo = f1.FacNo
INNER JOIN Offering o2 on o1.OffYear = o2.OffYear

You are on the right track. Joining the Offering table twice on the OffYear correctly gets you the combinations of courses in the same year. Since you want the names of the two faculty members, you also need to join the Faculty table twice:
SELECT f1.FacNo, f1.FacLastName, f2.FacNo, f2.FacLastName
FROM Offering o1
INNER JOIN Faculty f1
on o1.FacNo = f1.FacNo
INNER JOIN Offering o2
on o2.OffYear = o1.Offyea
INNER JOIN Faculty f2
on o2.FacNo = f2.FacNo
This will however include exact duplicate rows (e.g. when two faculty members had two courses in the same year), combinations of faculty members with themselves and duplicate combinations of names in reverse order (both [P1, Smith, P2, Peters] and [P2, Peters, P1, Smith]).
To get rid of the exact duplicates, use SELECT DISTINCT instead of SELECT. The other two problems can be easily fixed with one WHERE condition: By limiting results so that the first member's FacNo is smaller than the other's, unwanted combinations are filtered out.
SELECT DISTINCT f1.FacNo, f1.FacLastName, f2.FacNo, f2.FacLastName
FROM Offering o1
INNER JOIN Faculty f1
on o1.FacNo = f1.FacNo
INNER JOIN Offering o2
on o2.OffYear = o1.Offyear
INNER JOIN Faculty f2
on o2.FacNo = f2.FacNo
WHERE f1.FacNo < f2.FacNo
See this dB<>fiddle.

Related

How to write stored procedure in this case?

Database: training
Task: write a stored procedure for transferring a student from one group to another, while checking whether both groups have the same number of disciplines. This is, for example, in one group the number of students was 28, and in the other 20. So that after the procedure, the number was 27 and 21. The code for creating the database tables:...
CREATE DATABASE education
GO
USE education
CREATE TABLE control_type
(
control_type_id INT IDENTITY(1,1) PRIMARY KEY,
control_type_name VARCHAR(20) NOT NULL
);
CREATE TABLE category
(
category_id INT IDENTITY(1,1) PRIMARY KEY,
category_name VARCHAR(20) NOT NULL
);
CREATE TABLE subjects
(
subject_id INT IDENTITY(1,1) PRIMARY KEY,
subject_name VARCHAR(20) NOT NULL,
count_hours INT NOT NULL,
category_id INT NOT NULL
REFERENCES category (category_id)
ON DELETE CASCADE
);
CREATE TABLE groups
(
group_id INT IDENTITY(1,1) PRIMARY KEY,
group_name VARCHAR(20) NOT NULL,
course INT NOT NULL DEFAULT '1',
count_students INT NOT NULL,
count_hours INT NOT NULL
);
CREATE TABLE [session]
(
session_id INT IDENTITY(1,1) PRIMARY KEY,
name_last_prof VARCHAR(20) NOT NULL,
name_1st_prof VARCHAR(20) NOT NULL,
name_2nd_prof VARCHAR(20) NOT NULL,
session_date DATE NOT NULL,
control_type_id INT NOT NULL
REFERENCES control_type (control_type_id)
ON DELETE CASCADE,
group_id INT NOT NULL
REFERENCES groups (group_id)
ON DELETE CASCADE,
subject_id INT NOT NULL
REFERENCES subjects (subject_id)
ON DELETE CASCADE
);
CREATE INDEX idx_group ON groups (count_students);
CREATE INDEX idx_session ON [session] (name_last_prof);
CREATE INDEX idx_subject ON subjects (count_hours);
CREATE INDEX idx_category ON category (category_name);
CREATE INDEX idx_control_type ON control_type (control_type_name);
SET dateformat dmy;
INSERT INTO category VALUES ('�����������');
INSERT INTO category VALUES ('����*������');
INSERT INTO category VALUES ('�����������');
INSERT INTO category VALUES ('��������-���������');
INSERT INTO category VALUES ('���������');
INSERT INTO category VALUES ('��������');
INSERT INTO category VALUES ('������');
INSERT INTO category VALUES ('�������');
INSERT INTO category VALUES ('��������');
INSERT INTO category VALUES ('������');
INSERT INTO control_type VALUES ('����');
INSERT INTO control_type VALUES ('�����');
INSERT INTO subjects VALUES ('��������� ����',80,1);
INSERT INTO subjects VALUES ('��������� ��',75,1);
INSERT INTO subjects VALUES ('������ �������',90,3);
INSERT INTO subjects VALUES ('��������� ����������',100,3);
INSERT INTO subjects VALUES ('������������ �����',120,3);
INSERT INTO subjects VALUES ('���������',110,6);
INSERT INTO subjects VALUES ('��������',100,6);
INSERT INTO subjects VALUES ('�����������',120,6);
INSERT INTO subjects VALUES ('��������',80,6);
INSERT INTO subjects VALUES ('������',100,7);
INSERT INTO subjects VALUES ('������ ������',80,5);
INSERT INTO groups VALUES ('���-01-1',1,20,500);
INSERT INTO groups VALUES ('���-01-2',1,25,520);
INSERT INTO groups VALUES ('ϲ-171',3,23,550);
INSERT INTO groups VALUES ('ϲ-172',3,22,540);
INSERT INTO groups VALUES ('ʲ-181',2,30,490);
INSERT INTO groups VALUES ('ʲ-182',2,29,500);
INSERT INTO groups VALUES ('��-161',4,28,480);
INSERT INTO groups VALUES ('��-162',4,24,510);
INSERT INTO groups VALUES ('��-171',3,26,500);
INSERT INTO groups VALUES ('��-172',3,23,520);
INSERT INTO [session] VALUES ('�����','���','�������','22.06.2022',1,1,3);
INSERT INTO [session] VALUES ('����','����','�������','17.01.22',2,1,4);
INSERT INTO [session] VALUES ('������','³����','�������������','20.06.2022',2,2,3);
INSERT INTO [session] VALUES ('��������','���������','�������������','15.06.2022',2,2,2);
INSERT INTO [session] VALUES ('�����','�����','�������','20.01.22',1,5,8);
INSERT INTO [session] VALUES ('������','���������','����������','18.06.2022',2,6,7);
INSERT INTO [session] VALUES ('�����','�����','³��������','23.01.22',2,3,6);
INSERT INTO [session] VALUES ('�����������','������','��������','16.01.22',2,1,10);
INSERT INTO [session] VALUES ('������','������','����������','13.06.2022',1,2,2);
INSERT INTO [session] VALUES ('������','�����','��������','15.01.22',2,2,4);
I don't understand the logic of writing SQL queries in this case...

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.

Violation of PRIMARY KEY constraint PK_Casting

I'm trying to add a new data base through a script, but getting some errors, already tried to let out the double fields, but that didn't work for me.
USE master
GO
IF EXISTS (SELECT * FROM sysdatabases WHERE NAME = 'MijnFilms')
BEGIN
ALTER DATABASE MijnFilms SET SINGLE_USER WITH ROLLBACK IMMEDIATE
DROP DATABASE MijnFilms
END
GO
-- Creatie databank Bibliotheek
CREATE DATABASE MijnFilms
GO
USE MijnFilms
GO
--Creatie tabel AUTEUR
CREATE TABLE ACTEUR
(
Acteur_id int NOT NULL,
ActeurNaam nvarchar(40),
CONSTRAINT PK_Acteur PRIMARY KEY(acteur_id)
)
GO
--Creatie tabel CATEGORIE
CREATE TABLE CASTING
(
Film_id int NOT NULL,
Acteur_id int NOT NULL,
CONSTRAINT PK_Casting PRIMARY KEY(Film_id),
CONSTRAINT FK1_Casting FOREIGN KEY(Acteur_id) REFERENCES Acteur(acteur_id)
)
GO
--Creatie tabel BOEKEN
CREATE TABLE FILM
(
Film_id int NOT NULL,
Titel nvarchar(40),
Jaar smallint,
Score int,
Stemmen int,
CONSTRAINT FK1_Film FOREIGN KEY(Film_id) REFERENCES Casting(film_id),
)
GO
--Opvullen van de tabellen met testdata
INSERT INTO ACTEUR(Acteur_id, ActeurNaam) VALUES (1, 'Tom Hanks')
INSERT INTO ACTEUR(Acteur_id, ActeurNaam) VALUES (2, 'Helen Hunt')
INSERT INTO ACTEUR(Acteur_id, ActeurNaam) VALUES (3, 'Catherine Zeta Jones')
GO
INSERT INTO CASTING (Film_id, Acteur_id) VALUES (1, 1)
INSERT INTO CASTING (Film_id, Acteur_id) VALUES (1, 2)
INSERT INTO CASTING (Film_id, Acteur_id) VALUES (2, 1)
INSERT INTO CASTING (Film_id, Acteur_id) VALUES (2, 3)
GO
INSERT INTO FILM(Film_id, Titel, jaar, Score, Stemmen) VALUES (1, 'Cast Away', 2000, 75,1)
INSERT INTO FILM(Film_id, Titel, jaar, Score, Stemmen) VALUES (2, 'The Terminal', 2004, 62,1)
GO
Right now, I get an error:
Msg 2627, Level 14, State 1, Line 60
Violation of PRIMARY KEY constraint 'PK_Casting'. Cannot insert duplicate key in object 'dbo.CASTING'. The duplicate key value is (2).
Well, you're trying to insert a film_id of 1 (and 2) into casting twice but primary keys need to be unique.
You could use a composite primary key here, consisting of the film's and the actor's ID.
Also the film's ID should be the primary key in film and a foreign key in casting not the other way round. That requires film to be created before casting though. That also applies for the INSERTs -- film has to come before casting.
...
CREATE TABLE film
(film_id integer
NOT NULL,
titel nvarchar(40),
jaar smallint,
score integer,
stemmen integer,
CONSTRAINT pk_film
PRIMARY KEY (film_id));
CREATE TABLE acteur
(acteur_id integer
NOT NULL,
acteurnaam nvarchar(40),
CONSTRAINT pk_acteur
PRIMARY KEY (acteur_id));
CREATE TABLE casting
(film_id integer
NOT NULL,
acteur_id integer
NOT NULL,
CONSTRAINT pk_casting
PRIMARY KEY (film_id,
acteur_id),
CONSTRAINT fk1_casting
FOREIGN KEY (film_id)
REFERENCES film
(film_id),
CONSTRAINT fk2_casting
FOREIGN KEY (acteur_id)
REFERENCES acteur
(acteur_id));
...
INSERT INTO film ...
INSERT INTO acteur ...
INSERT INTO casting ...
You are creating the table with constraints
CREATE TABLE CASTING
(
Film_id int NOT NULL,
Acteur_id int NOT NULL,
CONSTRAINT PK_Casting PRIMARY KEY(Film_id),
CONSTRAINT FK1_Casting FOREIGN KEY(Acteur_id) REFERENCES Acteur(acteur_id)
)
GO
and then you are inserting duplicated records in the table
INSERT INTO CASTING (Film_id, Acteur_id) VALUES (1, 1)
INSERT INTO CASTING (Film_id, Acteur_id) VALUES (1, 2)
INSERT INTO CASTING (Film_id, Acteur_id) VALUES (2, 1)
INSERT INTO CASTING (Film_id, Acteur_id) VALUES (2, 3)
You need to remove the constraint or you need to make COMPOSITE KEY by creating the key on FILM_ID and ACTEUR_ID

Correct SQL Create Table Statement?

I've been stuck on this final table/data dictionary that I'm working on and I'm not quite sure on the syntax of the create table statement.
Data Dictionary:
TABLE NAME: Enrollment
Sid (Column Name)
NUMBER(Data Type)
5(Length)
blank(not null)
Y(PK)
Y(FK)
Blank(Check)
Csecid(Column Name)
NUMBER(Data Type)
8(Length)
blank(not null)
Y(PK)
Y(FK)
Blank(Check)
Grade(Column Name)
CHAR(Data Type)
1(Length)
blank(not null)
Blank(PK)
Blank(FK)
A,B,D,D,F,I,W(Checks).
Notes:
Sid is also defined as the PK on the STUDENT table.
Csecid is also defined as the PK on the COURSE_SECTION table.
I don't know how to define both Sid and Csecid in the Create table statement as both PK and FK. Please help. Thanks!
In my understanding you need to create a mapping table Enrollment for tables Student and Course_Section, because Student and Course_Section have many-to-many relationship.
Following lists the sample schema and create table queries:
-- Create Student Table
create table student(sid number(5) primary key, sname varchar2(100),
dob date);
-- Insert some data
insert into student values(1,'student1','01-feb-1990');
insert into student values(2,'student2','01-mar-1990');
insert into student values(3,'student3','01-apr-1990');
insert into student values(4,'student4','01-may-1990');
commit;
-- Create Course_Section Table
create table course_section(csecid number(8) primary key,
csname varchar2(30));
-- Insert some data
insert into course_section values(115,'CS1');
insert into course_section values(116,'CS2');
insert into course_section values(117,'CS3');
insert into course_section values(118,'CS4');
insert into course_section values(119,'CS5');
commit;
-- Since student and course_section have many-to-many relationship
-- One student can enroll to many courses
-- One course can be associated with many students
-- They need to be related using separate table
create table enrollment(sid number(5) not null,
csecid number(8) not null,
grade char(1) not null,
constraint e_pk primary key(sid, csecid),
foreign key (sid) references student(sid),
foreign key (csecid) references course_section(csecid),
constraint gc_constraint check (grade in ('A','B','C','D','F','I','W')));
-- Insert some records in enrollment
insert into enrollment values(1,115,'D');
insert into enrollment values(2,118,'C');
insert into enrollment values(1,118,'C');
insert into enrollment values(2,117,'A');
insert into enrollment values(4,116,'B');
insert into enrollment values(3,118,'I');
insert into enrollment values(4,118,'W');
commit;
Check this sqlfiddle to know more.

Foreign Key Not Populating with Primary Key Values

I have searched for an answer but am not finding it. I have 2 tables. Both have an auto-generated PK. The PK from table 2 is an FK in table 1. Since they are both auto-generated I assumed the FK in table 1 would populate with the value that is auto-generated from table 2 but it is not working. The FK in table 1 ends up null. Here is my SQL code for creating table 1:
CREATE TABLE Employee_tbl (
EmployeeID int PRIMARY KEY IDENTITY,
LastName varchar(20) not null,
FirstName varchar(20) not null,
Age varchar(3) not null,
JobID int FOREIGN KEY REFERENCES JobTitle_tbl(JobID),
)
and here is table 2:
create table JobTitle_tbl(
JobID int PRIMARY KEY IDENTITY,
EEO1Classification varchar(50) not null,
Exempt_nonexempt_status varchar(20) not null,
)
I also have some insert statements:
INSERT INTO Employee_tbl
(LastName, FirstName, Age)
Values
('Smith', 'John', '50'),
...
and:
INSERT into JobTitle_tbl (EEO1Classification, Job_title, )
VALUES ('Office/Clerical', 'Accounting Clerk', ),
Why is the FK value showing null when I query table 1?
The foreign keys will not auto-populate, as it doesn't know what foreign key to use. You need to either insert the rows into the JobTitle_tbl table, then select the IDs back out (or use ##identity if using sql server)
select id from JobTitle_tbl where Job_title = ''
Another option would be to update your insert statements to include the primary key, although you'll have to allow identity inserts first.
SET IDENTITY_INSERT JobTitle_tbl ON
into the JobTitle_tbl (id, title) values (1, 'Manager')
SET IDENTITY_INSERT JobTitle_tbl OFF
In either case, you'll need to then update your first insert statements with the ID that you have.
insert into Employee_tbl (LastName, FirstName, JobID) values ('Smith', 'John', 1)