0% found this document useful (0 votes)
15 views46 pages

GP6 Lab

Uploaded by

linmochen0910
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views46 pages

GP6 Lab

Uploaded by

linmochen0910
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

XIAMEN UNIVERSITY

XIAMEN MALAYSIA
UNIVERSITY MALAYSIA

Course Code : SOF202


Course Name : Database
Lecturer : Zamratul Asyikin binti Amran
Academic Session : 2023/09
Assessment Title : Lab Report
Submission Due Date : 29th December 2023

Prepared by : Student ID Student Name


DMT2209214 Lin Mochen
DMT2209206 Gao Zhihan
DMT2209211 Li Minjia
DMT2209244 Zhang Ruohan
DMT2209202 Chen Yuanxi

Date Received :

Feedback from Lecturer:

1 / 44 1
XIAMEN UNIVERSITY MALAYSIA

Mark:

Own Work Declaration

I/We acknowledge that my/our work will be examined for plagiarism or any other form
of academic misconduct, and that the digital copy of the work may be retained for future
comparisons.

I/We confirm that all sources cited in this work have been correctly acknowledged and
that I/we fully understand the serious consequences of any intentional or unintentional
academic misconduct.

In addition, I/we affirm that this submission does not contain any materials generated
by AI tools, including direct copying and pasting of text or paraphrasing. This work is
my/our original creation, and it has not been based on any work of other students (past
or present), nor has it been previously submitted to any other course or institution.

Signature:

Date: 31st December, 2023

2 / 44
Content
Task 1: Database Integrity ......................................................................................... 4
Task 2: SQL .............................................................................................................. 4
A: Table creation ............................................................................................... 4
B: Insert data ..................................................................................................... 7
C: SQL syntaxes queries ................................................................................... 11
Lin Mochen .............................................................................................. 11
Gao Zhihan .............................................................................................. 15
Li Minjia .................................................................................................. 18
Chen Yuanxi ............................................................................................ 19
Zhang Ruohan.......................................................................................... 22
Task 3: Trigger ........................................................................................................ 24
Before update .................................................................................................. 24
Before insert .................................................................................................... 27
After update..................................................................................................... 29
After inserte..................................................................................................... 34

3 / 44
Task 1: Database Integrity

Entity/Table Domain Integrity Entity Integrity Referential Integrity

SearchHistoryID
(FK),
User Not Null UserID (PK) LoanID (FK)

SearchHistory Not Null, Default SearchHistoryID (PK) UserID (FK)

UserID (FK),
Loan Not Null LoanID (PK) ContentID (FK)

UserID (FK),
FineHistory Not Null FineID (PK) LoanID (FK)

LocationID (FK),
Not Null, Check (type, ResourceAvailabilityI
Content status) ContentID (PK) D (FK)

Notification Not Null NotificationID (PK) -

ResourceAvailabilityI
ResourceAvailability Not Null D (PK) ContentID (FK)

Location Not Null LocationID (PK) -

Task 2: SQL

A: Table creation

CREATE DATABASE LibraryManagement;

use LibraryManagement;

CREATE TABLE Location (


4 / 44
LocationID VARCHAR(10) PRIMARY KEY NOT NULL,
RackNo VARCHAR(10) NOT NULL,
ShelfNo VARCHAR(10) NOT NULL
);

CREATE TABLE User (


UserID VARCHAR(10) PRIMARY KEY NOT NULL,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
Username VARCHAR(20) NOT NULL,
Password VARCHAR(50) NOT NULL,
Email VARCHAR(100) NOT NULL,
PhoneNo VARCHAR(15) NOT NULL,
Address VARCHAR(100),
MemberType VARCHAR(20) NOT NULL,
RegistrationDate DATE
);

CREATE TABLE Content (


ContentID VARCHAR(10) PRIMARY KEY NOT NULL,
Type VARCHAR(10),
Title VARCHAR(100) NOT NULL,
Author VARCHAR(50) NOT NULL,
Subject VARCHAR(50) NOT NULL,
PublicationDate DATE,
LocationID VARCHAR(10),
Price DECIMAL(10, 2),
CONSTRAINT FK_Content_Location FOREIGN KEY (LocationID)
REFERENCES Location(LocationID)

5 / 44
);

CREATE TABLE ResourceAvailability (


ResourceAvailabilityID VARCHAR(10) PRIMARY KEY NOT NULL,
IsAvailability TINYINT(1),
AvailabilityDate DATE,
ContentID VARCHAR(10) NOT NULL,
CONSTRAINT FK_ResourceAvailability_Content FOREIGN KEY (ContentID)
REFERENCES Content(ContentID)
);

CREATE TABLE Loan (


LoanID VARCHAR(10) PRIMARY KEY NOT NULL,
LoanDate DATE NOT NULL,
DueDate DATE,
ReturnedDate DATE,
FineAmount DECIMAL(10,2),
State VARCHAR(20),
UserID VARCHAR(10) NOT NULL,
ContentID VARCHAR(10) NOT NULL,
CONSTRAINT FK_Loan_UserID FOREIGN KEY (UserID) REFERENCES
User(UserID),
CONSTRAINT FK_Loan_ContentID FOREIGN KEY (ContentID)
REFERENCES Content(ContentID)
);

CREATE TABLE FineHistory (


FineID VARCHAR(10) PRIMARY KEY NOT NULL,
FineDate DATE,

6 / 44
FineDescription VARCHAR(255),
FineAmount DECIMAL(10,2),
UserID VARCHAR(10) NOT NULL,
LoanID VARCHAR(10) NOT NULL,
CONSTRAINT FK_FineHistory_UserID FOREIGN KEY (UserID)
REFERENCES User(UserID),
CONSTRAINT FK_FineHistory_LoanID FOREIGN KEY (LoanID)
REFERENCES Loan(LoanID)
);

CREATE TABLE Notification (


NotificationID VARCHAR(10) PRIMARY KEY NOT NULL,
NotificationType VARCHAR(20),
Message VARCHAR(255),
NotificationDate DATETIME NOT NULL
);

CREATE TABLE SearchHistory (


SearchHistoryID VARCHAR(10) PRIMARY KEY NOT NULL,
SearchQuery VARCHAR(255),
SearchDate DATE,
UserID VARCHAR(10),
FOREIGN KEY fk_SearchHistory_User(UserID) REFERENCES User(UserID)
);

B: Insert data

INSERT INTO User (UserID, FirstName, LastName, Username, Password, Email,


PhoneNo, Address, MemberType, RegistrationDate)

7 / 44
VALUES
('A001', 'John', 'Doe', 'john_doe', 'password123', '[email protected]', '1234567890',
'123 Main St', 'Administrative Staff', '2021-01-01'),
('S001', 'Jane', 'Smith', 'jane_smith', 'pass456', '[email protected]', '9876543210', '456
Oak St', 'Student', '2021-02-15'),
('S002', 'Bob', 'Johnson', 'bob_j', 'secret789', '[email protected]', '5556667777', '789
Pine St', 'Student', '2020-03-20'),
('P001', 'Alice', 'Brown', 'alice_b', 'topsecret', '[email protected]', '3332221111', '321
Elm St', 'Professor', '2022-04-10'),
('A002', 'Charlie', 'Green', 'charlie_g', 'classified', '[email protected]',
'9998887777', '654 Birch St', 'Administrative Staff', '2023-05-05'),
('L001', 'Eva',' Martinez', 'eva_m', 'pass789', '[email protected]', '1112223333', '987
Oak St', 'libarian', '2013-06-01'),
('P002', 'Michael',' Lee', 'mike_l', 'keypass', '[email protected]', '4445556666', '654
Elm St', 'Professor', '2021-06-15'),
('P003', 'Sophie',' Taylor', 'sophie_t', 'secure123', '[email protected]', '7778889999',
'321 Pine St', 'Professor', '2022-07-01'),
('S003', 'David', 'Wright', 'david_w', 'mypass789', '[email protected]', '2223334444',
'768 Maple St', 'Student', '2023-07-15'),
('A003', 'Emily', 'Johnson', 'emily_j', 'mypassword', '[email protected]',
'6667778888', '932 Cherry Ln', 'Administrative Staff', '2023-08-01');

INSERT INTO location (locationID, rackNo, shelfNo)


VALUES
('L1', 'R101', 'S1'),
('L2', 'R102', 'S2'),
('L3', 'R103', 'S3'),
('L4', 'R104', 'S4'),

8 / 44
('L5', 'R105', 'S5');

INSERT INTO Content (ContentID, Type, Title, Author, Subject, PublicationDate,


LocationID, Price)
VALUES
('C1', 'Book', 'The Art of SQL', 'John Doe', 'Database', '2022-01-15', 'L1', 24.99),
('C2', 'Magazine', 'Tech Today', 'Jane Smith', 'Technology', '2022-02-01', 'L2', 22.99),
('C3', 'Journal', 'Data Science Review', 'Bob Johnson', 'Data Science', '2022-03-10', 'L3',
28.99),
('C4', 'Book', 'Programming Basics', 'Alice Brown', 'Programming', '2022-04-05', 'L4',
26.99),
('C5', 'Magazine', 'Science News', 'Charlie Green', 'Science', '2022-05-20', 'L5', 25.99),
('C6', 'Book', 'Advanced Mathematics', 'Emma Wilson', 'Mathematics', '2022-06-15',
'L1', 27.50),
('C7', 'Journal', 'World History Review', 'Liam Nguyen', 'History', '2022-07-10', 'L2',
23.75),
('C8', 'Book', 'Modern Physics', 'Olivia Kim', 'Physics', '2022-08-05', 'L3', 29.95),
('C9', 'Magazine', 'Global Economics', 'Ethan Brown', 'Economics', '2022-09-20', 'L4',
21.99),
('C10', 'Journal', 'Literary Classics', 'Sophia Garcia', 'Literature', '2022-10-25', 'L5',
24.89);

INSERT INTO Loan (LoanID, LoanDate, DueDate, UserID, ContentID)


VALUES
('L1', '2023-01-25', '2023-02-25', 'A001', 'C1'),
('L2', '2023-02-15', '2023-03-15', 'S001', 'C2'),
('L3', '2023-03-25', '2023-04-25', 'S002', 'C3'),
('L4', '2023-04-10', '2023-05-10', 'P001', 'C4'),

9 / 44
('L5', '2023-05-05', '2023-06-05', 'A002', 'C5');

INSERT INTO resourceAvailability (ResourceAvailabilityID, isAvailability,


availabilityDate, contentID)
VALUES
('RA1', 1, '2023-01-20', 'C1'),
('RA2', 0, '2023-02-10', 'C2'),
('RA3', 1, '2023-03-15', 'C3'),
('RA4', 1, '2023-04-25', 'C4'),
('RA5', 0, '2023-05-30', 'C5');

INSERT INTO finehistory (fineID, fineDate, fineDescription, fineAmount, userID,


loanID)
VALUES
('F1', '2022-02-21', 'Late return', 5.00, 'A001', 'L1'),
('F2', '2022-03-12', 'No fine', 0.00, 'S001', 'L2'),
('F3', '2022-04-21', 'Late return', 8.50, 'S002', 'L3'),
('F4', '2022-05-06', 'No fine', 0.00, 'P001', 'L4'),
('F5', '2022-06-02', 'Late return', 3.00, 'A002', 'L5');

INSERT INTO notification (notificationID, notificationType, message,


notificationDate)
VALUES
('N1', 'Reminder', 'Return your book on time', '2022-02-20 10:00:00'),
('N2', 'Information', 'New magazine available', '2022-03-01 08:30:00'),
('N3', 'Alert', 'Overdue journal', '2022-03-18 15:45:00'),
('N4', 'Reminder', 'Upcoming due date', '2022-04-05 12:00:00'),

10 / 44
('N5', 'Information', 'Science magazine released', '2022-05-15 09:00:00');

insert into searchhistory (searchHistoryID,searchQuery,searchDate,UserID)


values
('sea1','Check if this book is available','2023-01-28','A001'),
('sea2','Find the location of this book','2023-02-21','S001'),
('sea3','Query personal borrowing information','2023-03-28','S002'),
('sea4','Find the location of this book','2023-04-12','P001'),
('sea5','View past due notices','2023-06-03','A002');

C: SQL syntaxes queries

Lin Mochen
1. Logical Operators Query:
Find all books that are either categorized as 'Magazine' or 'Non-Magazine' and have
been checked out after 1/5/2022.

SELECT *
FROM content
WHERE (type = 'Magazine' OR type = 'Non-Magazine')
AND PublicationDate > '2022-05-01';

2. Arithmetic Operators Query

11 / 44
Calculates the total fine amount for each user. It combines information from the Loan
table to calculate fines based on different states ('Normal', 'LateReturn', 'Damage', 'Lost')
and adds the FineAmount from the FineHistory table to the total fine calculation for
each user.
TotlaFine is calculated according to the following conditions: for each user, if the status
is "Normal", the amount of the fine is zero; if the status is "LateReturn", the amount of
the fine is calculated according to the number of days of delayed return; if the status is
"Damage", the amount of the fine is the price of the content; and if the status is "Lost",
the amount of the fine is twice the price of the content.
Before calculating the amount of a user's fine, update data is needed to keep track of
each user's book returns. This is the comment that updates the data:

START TRANSACTION;

UPDATE Loan
SET ReturnedDate = CASE LoanID
WHEN 'L1' THEN '2023-02-20'
WHEN 'L2' THEN '2023-04-15'
WHEN 'L3' THEN '2023-03-30'
WHEN 'L4' THEN '2023-04-20'
WHEN 'L5' THEN '2023-05-15'
WHEN 'L6' THEN '2023-07-09'
WHEN 'L7' THEN '2023-10-15'
WHEN 'L8' THEN '2023-11-20'
WHEN 'L9' THEN '2023-10-15'
WHEN 'L10' THEN '2023-11-13'
END,
State = CASE LoanID
WHEN 'L1' THEN 'Normal'
WHEN 'L2' THEN 'LateReturn'

12 / 44
WHEN 'L3' THEN 'Normal'
WHEN 'L4' THEN 'Damage'
WHEN 'L5' THEN 'Lost'
WHEN 'L6' THEN 'Normal'
WHEN 'L7' THEN 'LateReturn'
WHEN 'L8' THEN 'LateReturn'
WHEN 'L9' THEN 'Normal'
WHEN 'L10' THEN 'Damage'
END
WHERE LoanID IN ('L1', 'L2', 'L3', 'L4', 'L5', 'L6', 'L7', 'L8', 'L9', 'L10');

COMMIT;

Query:

SELECT
U.UserID,
COALESCE(SUM(
CASE
WHEN L.State = 'Normal' THEN 0
WHEN L.State = 'LateReturn' THEN
CASE
WHEN DATEDIFF(L.ReturnedDate, L.DueDate) > 10
THEN 5 + (DATEDIFF(L.ReturnedDate, L.DueDate) - 10)
ELSE 5
END
WHEN L.State = 'Damage' THEN C.Price
WHEN L.State = 'Lost' THEN 2 * C.Price
ELSE 0
END + FH.FineAmount
), 0) AS TotalFine

13 / 44
FROM User U
LEFT JOIN Loan L ON U.UserID = L.UserID
LEFT JOIN FineHistory FH ON L.LoanID = FH.LoanID
LEFT JOIN Content C ON L.ContentID = C.ContentID
GROUP BY U.UserID;

3. Join Query (INNER JOIN)


Display a list of users along with the titles of the books they have currently checked out.
The query retrieves the UserID, FirstName, and LastName from the User table and
matches it with the corresponding checked-out book titles from the Content table, based
on the relationships defined by Loan and Content IDs.

SELECT
U.UserID,
U.FirstName,
U.LastName,
C.Title AS CheckedOutBookTitle
FROM User U
14 / 44
INNER JOIN Loan L ON U.UserID = L.UserID
INNER JOIN Content C ON L.ContentID = C.ContentID;

Gao Zhihan
1. Write a query to display userID, FullName, MemberType, contentID, LoanDate,
Title from user, Loan, and Content table, whose MemberType is student or professor.
Implement an INNER JOIN to include users and their corresponding information.
(This query uses Logical Operator IN and Join Query INNER, this is a two inner
between three tables)

SELECT user.userID,
concat(user.FirstName,' ',user.Lastname) As'FullName',
user.MemberType,Loan.contentID,Loan.LoanDate,content.Title
FROM user
Inner join loan on user.userID=loan.userID
Inner join content on loan.contentID=content.contentID
WHERE MemberType IN ('student', 'professor');

15 / 44
2. Write a query to display UserID, FullName, ContentID, LoanDate from User and
Loan table. Implement a LEFT JOIN to include all users and their corresponding
loan information, showing null where there are no loans and list in descending order
by LoanDate.
(This query use Join Query LEFT, Logical Operator ORDER BY, and I learn a new
function COALESCE as a replacement value)

SELECT user.userID,
concat(user.FirstName,' ',user.Lastname) As'FullName',
COALESCE(loan.contentID, 'No loan available') AS ContentID, loan.LoanDate
FROM user
LEFT JOIN loan ON user.userID = loan.userID
ORDER BY loan.LoanDate DESC;

16 / 44
(*This query was implemented before I created before insert trigger, but after I created
the update trigger to display the situation: No loan available.)

3. Write a query to diplay userID, FullName, RegistrationDate, fineAmount, Title,


FineAmount, and calculate MembershipDuration from table user, loan, content, and
finehistory, and display whose RegistrationDate>1 years
(This query use two inner and a left join between 4 tables, "Perform an inner join
between the user table and the loan table, then perform an inner join between the loan
table and the content table, and finally, perform a left join between the user table and
the finehistory table.")

17 / 44
Li Minjia
1. Logical Operators -‘LIKE’:
Write a query to display the list of resource information where Title starts with T.

SELECT * FROM librarymanagement.content


where Title like 'T%';

2. Logical Operators-‘between’:
Write a query to display the ContentID, Title, Type, Author, and PublicationDate of the
resources published between 9th March 2022 and 19th May 2022. Order by ContentID.

select ContentID, Type, Author, PublicationDate


from librarymanagement.content
where PublicationDate between '2022-03-09' and '2022-05-19'
order by ContentID;

3. Logical Operators-‘COUNT’:
Write a query to count how many times each content has been borrowed, ordered by
ContentID.
18 / 44
select content.ContentID, content.Title,
Count(content.ContentID) as 'Total Loans'
from loan inner join content ON content.ContentID = loan.ContentID
Group by ContentID;

Chen Yuanxi
1. INER JOIN and ORDER BY
Queries all users who have borrowed the book "The Art of SQL" and the date they
borrowed it, sorted in ascending order by the date they borrowed it.

SELECT User.UserID, CONCAT(User.FirstName, ' ', User.LastName) AS FullName,


loan.LoanDate
FROM User
INNER JOIN loan ON User.UserID = loan.userID
INNER JOIN content ON loan.contentID = content.contentID
WHERE content.title = 'The Art of SQL'
ORDER BY loan.LoanDate ASC;

19 / 44
2. LEFT JOIN and CASE
Lists all users and their last checkout date. If the user has no borrowing history, "No
Loan Record" is displayed.

SELECT User.UserID, CONCAT(User.FirstName, ' ', User.LastName) AS FullName,


CASE
WHEN loan.loanDate IS NULL THEN 'No Loan Record'
ELSE loan.loanDate
END AS LastLoanDate
FROM User
LEFT JOIN loan ON User.UserID = loan.userID
ORDER BY User.UserID;

20 / 44
3. RIGHT JOIN and BETWEEN
Lists all loan records for books borrowed In the second half of 2023 (30th June through
31st December), including book titles and loan dates.

SELECT loan.loanID, content.title, loan.loanDate


FROM loan
RIGHT JOIN content ON loan.contentID = content.contentID
WHERE loan.loanDate BETWEEN '2023-06-30' AND '2023-12-31';

21 / 44
Zhang Ruohan
1. This query uses logical operators (AND, OR) to filter users who have returned their
loans on time or without penalties:

SELECT DISTINCT User.*


FROM User
JOIN loan ON User.UserID = loan.userID
LEFT JOIN finehistory ON User.UserID = finehistory.userID
WHERE (loan.returnedDate <= loan.dueDate OR loan.returnedDate IS NULL)
AND (finehistory.fineID IS NULL OR finehistory.fineAmount = 0);

2. This query uses the sum() aggregation function to calculate the total amount of fines
for each user:

SELECT User.UserID, concat(User.firstname,User.lastname)as 'fullname',


sum(finehistory.fineAmount) AS averageFineAmount
FROM User
LEFT JOIN finehistory ON User.UserID = finehistory.userID
GROUP BY User.UserID,fullname;
22 / 44
3. Retrieve details of the content, its availability status and the users who borrowed it:

SELECT
C.ContentID,
C.Title,
C.Author,
R.IsAvailability,
L.LoanDate,
L.DueDate,
L.ReturnedDate,
U.UserID,
concat(U.firstname,U.lastname)as 'fullname'
FROM Content C
23 / 44
JOIN ResourceAvailability R ON C.ContentID = R.ContentID
LEFT JOIN Loan L ON C.ContentID = L.ContentID
LEFT JOIN User U ON L.UserID = U.UserID;

Task 3: Trigger

Before update
This is when I have not created any trigger, we can see that ReturenedDate, FineAmount,
and State is null.

The following that I create before update trigger in the table ‘Loan’.
24 / 44
This trigger achieves the function is that if update the Loan table, then FineAmount can
be calculated as follows if late return then the fine is Excess days*0.5, if damage then
the fine equal to the book price, if lost then the fine equal to the book price*2.

DELIMITER //
CREATE TRIGGER before_update_CalculateFine
BEFORE UPDATE ON Loan
FOR EACH ROW
IF NEW.ReturnedDate IS NOT NULL AND NEW.ReturnedDate > OLD.DueDate
THEN
SET NEW.FineAmount = DATEDIFF(NEW.ReturnedDate, OLD.DueDate)
* 0.5;
ELSEIF NEW.State = 'Damage' THEN
SET NEW.FineAmount = (SELECT price FROM content WHERE
ContentID = NEW.ContentID);
ELSEIF NEW.State = 'Lost' THEN
SET NEW.FineAmount = (SELECT price FROM content WHERE
ContentID = NEW.ContentID) * 2;
ELSE
SET NEW.FineAmount = 0.00;
END IF;
//DELIMITER ;
Show triggers

Then I update the Loan table

UPDATE Loan

25 / 44
SET ReturnedDate = '2023-02-20', State = 'Normal'
WHERE LoanID = 'L1';
UPDATE Loan
SET ReturnedDate = '2023-04-15', State = 'LateReturn'
WHERE LoanID = 'L2';
UPDATE Loan
SET ReturnedDate = '2023-03-30', State = 'Normal'
WHERE LoanID = 'L3';
UPDATE Loan
SET ReturnedDate = '2023-04-20', State = 'Damage'
WHERE LoanID = 'L4';
UPDATE Loan
SET ReturnedDate = '2023-05-15', State = 'Lost'
WHERE LoanID = 'L5';
Select * from Loan

26 / 44
This is evidence that I successfully create before update in Loan table.
Before insert
I will create a before insert trigger to ensure that if I insert LoanDate, then the table will
automatically generate DueDate (one month later)
First, I insert new values to see if we don’t have before insert trigger, and then what the
Loan table will be like.

INSERT INTO Loan (LoanID, LoanDate, UserID, ContentID)


values
('L6', '2023-07-01','L001', 'C6'),
('L7', '2023-08-15','P002', 'C7');
select * from Loan;

We can see that we cannot get DueDate.

The following that I create before insert trigger in the table ‘Loan’.

CREATE TRIGGER before_insert_DueDate


BEFORE INSERT ON Loan
FOR EACH ROW
SET NEW.DueDate = DATE_ADD(NEW.LoanDate, INTERVAL 1 MONTH);
show triggers;

27 / 44
We can see that before insert trigger has been created.

Then I insert new values ’L8’,‘L9’,‘L10’, we can see that the DueDate can be generated
automatically.

This is evidence that I successfully create before update in Loan table.

To facilitate queries and show the availability of triggers, I will update the table again.
The following table shows when I insert new values, we can see that before insert
played a role.

28 / 44
The following table is when updating the Loan table, It can calculate FineAmount,
before update played a role.

After updating the loan table – about FineHistory table :

Before creating a trigger:


The Loan table before update:

The FineHistory table before update:

29 / 44
The Loan table after updating:

UPDATE Loan

SET ReturnedDate = '2023-02-20', State = 'Normal'

WHERE LoanID = 'L1';

UPDATE Loan

SET ReturnedDate = '2023-04-15', State = 'LateReturn'

WHERE LoanID = 'L2';

The FineHistory table after updating:

30 / 44
We can see that the FineHistory table has not been updated despite the new fines.

Create trigger:
Let's create a trigger to solve this problem:

-- trigger after update

Delimiter//

create trigger after_update_loan

after update on Loan

for each row

-- set the condition

BEGIN

IF new. State != 'Normal' then

insert into finehistory(FineDate, FineDescription, FineAmount, UserID,


LoanID)

values(new. ReturnedDate, new. State, new. FineAmount, old. UserID,


old. LoanID);

END IF;

END; //

Delimiter;

31 / 44
After creating the trigger, try updating the Loan table again.

The Loan table after the Update:

UPDATE Loan

SET ReturnedDate = '2023-03-30', State = 'Normal'

WHERE LoanID = 'L3';

UPDATE Loan

SET ReturnedDate = '2023-04-20', State = 'Damage'

WHERE LoanID = 'L4';

32 / 44
FineHistory table after Updat:

Update another set of data:

UPDATE Loan

SET ReturnedDate = '2023-05-15', State = 'Lost'

WHERE LoanID = 'L5';

33 / 44
As you can see, our problem has been successfully solved, and after updating the loan
table, the record of the fine will be automatically recorded in the finehistory table,
which can help the administrator to review the damage condition of resources or
financial reconciliation.

After inserting into the Loan Table – about ResourceAvailability table:

Before creating a trigger:


When we don't create a trigger, we find that after inserting a loan record, the available
status of the corresponding resource in ResourceAvailability is not updated, which
may mislead borrowers:

ResourceAvailability table before Insert into loan table:

The loan table after inserting a set of data:

INSERT INTO Loan (LoanID, LoanDate, UserID, ContentID)

VALUES

('L6', '2023-07-01', 'L001', 'C1');

SELECT * FROM librarymanagement.loan;

34 / 44
The ResourceAvailability table after inserting a set of data into the loan table:

We can see that the Resource with ContentID = 'C1' has been borrowed, but the state
of "IsAvailability" and "AvailabilityDate" have not changed. "AvailabilityDate"
represents the time when the resource can be borrowed, and should be set to the day
when the resource is estimated to be returned, that is, "DueDate".

Create trigger:
We solve this problem by creating a trigger:

-- trigger after insert

create trigger after_insert_loan_resource

After insert on Loan

for each row

35 / 44
-- set the condition

Update ResourceAvailability

set IsAvailability = IsAvailability - 1, AvailabilityDate = new. DueDate

where ContentID = new. ContentID;

show triggers;

Now insert another set of data:

INSERT INTO Loan (LoanID, LoanDate, UserID, ContentID)

VALUES

('L7', '2023-08-15', 'P002', 'C3');

SELECT * FROM librarymanagement.loan;

The Loan table after Insert:

36 / 44
The ResourceAvailability table after Insert:

We find that the "IsAvailability" status of a resource with ContentID 'C3' has changed
from 1 to 0, indicating that the resource has been borrowed and there are no resources
to borrow. In addition, the "AvailabilityDate" of the Resource with the ContentID of
'C3' has been changed to the corresponding "DueDate" in the Loan table

Insert another set of data and see:

INSERT INTO Loan (LoanID, LoanDate, UserID, ContentID)

VALUES

('L8', '2023-09-20', 'P003', 'C4');

SELECT * FROM librarymanagement.loan;

37 / 44
After updating the Loan Table – about ResourceAvailability table:
When the reader returns the book, that is, after the loan table is updated, the status of
the ResourceAvailability table should be updated for the corresponding section. As
long as the status of the book is not 'Lost' or 'Damage', the value of 'IsAvailability'
need to increase by 1, which means that one more resource is available to borrow.
Also, ‘AvailabilityDate’ needs to be changed to ‘ReturnedDate’.

Before creating a trigger:


Before creating a trigger, we updated a set of data and found that changes to the loan
table did not cause updates to the ResourceAvailability table.

The loan table before update:

38 / 44
The ResourceAvailability table before update:

The loan table after update:

UPDATE Loan

SET ReturnedDate = '2023-07-29', State = 'Normal'

WHERE LoanID = 'L6';

UPDATE Loan

SET ReturnedDate = '2023-09-20', State = 'LateReturn'

WHERE LoanID = 'L7';

UPDATE Loan

39 / 44
SET ReturnedDate = '2023-10-15', State = 'Lost'

WHERE LoanID = 'L8';

SELECT * FROM librarymanagement.loan;

The ResourceAvailability table after update:

We found that the state of the resource did not change accordingly, which is not good.

40 / 44
Create trigger:
Create a trigger to solve this problem:

-- trigger after update

Delimiter//

create trigger after_update_loan_resource

after update on Loan

for each row

-- set the condition

BEGIN

IF new. State != 'Damage' and new. State != 'Lost' then

Update ResourceAvailability

set IsAvailability = IsAvailability + 1, AvailabilityDate = new.


ReturnedDate

where ContentID = old. ContentID;

END IF;

END; //

Delimiter;

show triggers;

41 / 44
To restore the Loan table to its previous state:

The current ResourceAvailability table:

Update the data in the loan table:

42 / 44
UPDATE Loan

SET ReturnedDate = '2023-07-29', State = 'Lost'

WHERE LoanID = 'L6';

UPDATE Loan

SET ReturnedDate = '2023-09-20', State = 'LateReturn'

WHERE LoanID = 'L7';

UPDATE Loan

SET ReturnedDate = '2023-10-15', State = 'Normal'

WHERE LoanID = 'L8';

SELECT * FROM librarymanagement.loan;

The loan table after the Update:

ResourceAvailability table after Update:

43 / 44
We find that the "IsAvailability" value of the Resource corresponding to ContentID =
'C3', 'C4' changes accordingly, while the "IsAvailability" value of the Resource
corresponding to ContentID = 'C1' does not increase because the state of the Resource
corresponding to ‘C1’ is "Lost" and cannot be increased.

44 / 44
APPENDIX 1
MARKING RUBRICS

Component Percentage
Lab Report (Group) 13.5%
Title (%)
Score and Descriptors
10 - 8 7-5 4-0 Weight
Criteria Marks
(%)
Outstanding - Excellent - Good - Above Average -
Below Average - Poor
Very Good Average
TASK 1 (15 Marks)
Domain Can identify
Identifies all of the main Was able to 5
Integrity the key parts
parts of the concepts and identify key Cannot identify important
of concepts
Entity has a high level of components elements of the integrity
and 5
Integrity understanding of the of the concept and has difficulty
demonstrate
concepts' relationships. An concepts. recognizing the
awareness of
example was given to An example relationship between
Referential the links
elaborate more on the given is concepts and applications. 5
Integrity between the
integrity concepts. acceptable.
concepts.
TASK 2A, & 2B (30 Marks)
• All of the tables • Most of the tables • Some of the tables
specified in the project specified in the project specified in the
requirements were requirements were project requirements
Database created. created. were partially
Design • Tables that are fully • Choose the majority of the constructed.
15
(Create & populated with the primary and foreign keys • The name of the table
Insert Data) relevant data pieces correctly while adhering did not correspond to
and mirror the E-ERD to the naming convention. its data items.
design.

• Tables have been • Tables have been filled • Most of the primary
appropriately named with the majority of the and foreign keys were
concerning their data data elements described in chosen incorrectly,
elements. the E-ERD design. Data although the naming
• Select all primary and items were entered into convention was
foreign keys correctly tables with minimal followed.
while adhering to the keypunch errors. • Tables are populated 15
naming standard. with minimum data
• Data items were elements defined in
inserted into tables the E-ERD design
correctly, with no project. When
keypunch errors. inserting data items
into tables, there are
several keypunch
errors.
TASK 3C (35 Marks)
• Query is adequate and
• Query fits the data well
does not twist the data.
and makes it easy to
interpret. • Used multiple database
Logical table to filter data with.
• Used multiple database
operators, • The written query is very • Query seriously twist
table to filter data with.
comparison, satisfactory. the data interpreting
• The query was written
arithmetic,
professionally. • Adequate way of writing almost impossible. 35
case queries and satisfactory. • No output table.
• Used multiple syntax to
expression &
show the creativity of • Output tables retrieved
Join queries. with a simple/ average
the queries.
complexity representation
• Output tables retrieved.
of SQL.

TASK 3 (10 Marks)

• Demonstrates a
limited understanding
of the triggering
concepts with an
•Show fully understand
• Understands the concepts example but without
the SQL Trigger in the
and triggers applications. an output.
SQL Trigger database design with 10
Showed a good example • Demonstrates a
proper examples with
with output. limited understanding
output.
of the triggering
concepts but without
any proper examples
and output.

TOTAL 90

You might also like