sqlite query for best selling artists - mysql

I am working on the basic chinook database, and am trying to write a sqlite query to create a view called v10BestSellingArtists for the 10 bestselling artists based on the total quantity of tracks sold (named as TotalTrackSales) order by TotalTrackSales in descending order. TotalAlbum is the number of albums with tracks sold for each artist.
I can write queries for both of them separately, but I can't figure out how to merge them.
But I want one query with the columns: Artist, TotalAlbum TotalTrackSales.
Can anyone tell me how to do this using only one select statement?
Any help is appreciated.
The schema for the album table:
[Title] NVARCHAR(160) NOT NULL,
[ArtistId] INTEGER NOT NULL,
FOREIGN KEY ([ArtistId]) REFERENCES "artists" ([ArtistId])
artists table :
[ArtistId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
[Name] NVARCHAR(120)
tracks table schema:
[TrackId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
[Name] NVARCHAR(200) NOT NULL,
[AlbumId] INTEGER,
[MediaTypeId] INTEGER NOT NULL,
[GenreId] INTEGER,
[Composer] NVARCHAR(220),
[Milliseconds] INTEGER NOT NULL,
[Bytes] INTEGER,
[UnitPrice] NUMERIC(10,2) NOT NULL,
FOREIGN KEY ([AlbumId]) REFERENCES "albums" ([AlbumId])
ON DELETE NO ACTION ON UPDATE NO ACTION,
FOREIGN KEY ([GenreId]) REFERENCES "genres" ([GenreId])
ON DELETE NO ACTION ON UPDATE NO ACTION,
FOREIGN KEY ([MediaTypeId]) REFERENCES "media_types" ([MediaTypeId])
ON DELETE NO ACTION ON UPDATE NO ACTION
table invoice_items:
[InvoiceLineId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
[InvoiceId] INTEGER NOT NULL,
[TrackId] INTEGER NOT NULL,
[UnitPrice] NUMERIC(10,2) NOT NULL,
[Quantity] INTEGER NOT NULL,
FOREIGN KEY ([InvoiceId]) REFERENCES "invoices" ([InvoiceId])
ON DELETE NO ACTION ON UPDATE NO ACTION,
FOREIGN KEY ([TrackId]) REFERENCES "tracks" ([TrackId])
ON DELETE NO ACTION ON UPDATE NO ACTION

Related

MySQL - Many-To-Many Relationship between three entities

I am having trouble figuring out the best design for my many-to-many relationship in my database. My project allows users to create what we are calling log alarms. A log alarm will check if a given log meets certain criteria and, if so, it will send a message to an AWS SNS topic. What I want to do is relate log alarms to AWS SNS topics. I also want to relate which user assigned that log alarm to that AWS SNS topic.
I have a table class XRefUserLogAlarmSNSTopic. It has three foreign keys. The goal of this table is to relate which SNS topics are related to what log alarms and to indicate which user made the relation. This seems rather messy to me and I get all sorts of errors when I try to create new log alarms or join tables in Spring JPA. My question is, is there are better database structure for what I am trying to achieve
UserId INT NOT NULL AUTO_INCREMENT,
Username VARCHAR(50) NOT NULL,
Password TEXT NOT NULL,
Email VARCHAR(255) NOT NULL,
Dashboard LONGTEXT NOT NULL,
PRIMARY KEY (UserId),
UNIQUE (Username),
UNIQUE (Email)
);
CREATE TABLE SNSTopics (
SNSTopicId INT NOT NULL AUTO_INCREMENT,
TopicName VARCHAR(50) NOT NULL,
TopicArn VARCHAR(255) NOT NULL,
PRIMARY KEY (SNSTopicId),
UNIQUE (TopicName),
UNIQUE (TopicArn)
);
CREATE TABLE LogGroups (
LogGroupId INT NOT NULL AUTO_INCREMENT,
Name VARCHAR(255) NOT NULL,
PRIMARY KEY (LogGroupId),
UNIQUE (Name)
);
CREATE TABLE Keywords (
KeywordId INT NOT NULL AUTO_INCREMENT,
Word VARCHAR(70),
PRIMARY KEY (KeywordId),
UNIQUE (Word)
);
CREATE TABLE LogAlarms (
LogAlarmId INT NOT NULL AUTO_INCREMENT,
LogLevel VARCHAR(5) NOT NULL CHECK (LogLevel IN ('TRACE', 'DEBUG', 'INFO', 'WARN', 'ERROR')),
Comparison VARCHAR(2) CHECK (Comparison IN ('==', '<', '<=', '>', '>=')),
AlarmName VARCHAR(255) NOT NULL,
KeywordRelationship CHAR(3) CHECK (KeywordRelationship IN ('ANY', 'ALL', NULL)),
PRIMARY KEY (LogAlarmId),
UNIQUE (AlarmName)
);
CREATE TABLE MetricAlarms (
MetricAlarmId INT NOT NULL AUTO_INCREMENT,
AlarmArn VARCHAR(100) NOT NULL,
PRIMARY KEY (MetricAlarmId),
UNIQUE (AlarmArn)
);
CREATE TABLE XRefUserMetricAlarm (
UserMetricAlarmId INT NOT NULL AUTO_INCREMENT,
UserId INT NOT NULL,
MetricAlarmId INT NOT NULL,
PRIMARY KEY (UserMetricAlarmId),
FOREIGN KEY (UserId) REFERENCES Users(UserId) ON DELETE CASCADE,
FOREIGN KEY (MetricAlarmId) REFERENCES MetricAlarms(MetricAlarmId) ON DELETE CASCADE,
UNIQUE (UserId, MetricAlarmId)
);
CREATE TABLE XRefLogAlarmLogGroup (
LogAlarmLogGroupId INT NOT NULL AUTO_INCREMENT,
LogAlarmId INT NOT NULL,
LogGroupId INT NOT NULL,
PRIMARY KEY (LogAlarmLogGroupId),
FOREIGN KEY (LogAlarmId) REFERENCES LogAlarms(LogAlarmId) ON DELETE CASCADE,
FOREIGN KEY (LogGroupId) REFERENCES LogGroups(LogGroupId) ON DELETE CASCADE,
UNIQUE (LogAlarmId, LogGroupId)
);
CREATE TABLE XRefLogAlarmKeyword (
LogAlarmKeywordId INT NOT NULL AUTO_INCREMENT,
LogAlarmId INT NOT NULL,
KeywordId INT NOT NULL,
PRIMARY KEY (LogAlarmKeywordId),
FOREIGN KEY (LogAlarmId) REFERENCES LogAlarms(LogAlarmId) ON DELETE CASCADE,
FOREIGN KEY (KeywordId) REFERENCES Keywords(KeywordId) ON DELETE CASCADE,
UNIQUE (LogAlarmId, KeywordId)
);
CREATE TABLE XRefUserLogAlarmSNSTopic (
UserLogAlarmSNSTopicId INT NOT NULL AUTO_INCREMENT,
LogAlarmId INT NOT NULL,
SNSTopicId INT NOT NULL,
UserId INT NOT NULL,
PRIMARY KEY (UserLogAlarmSNSTopicId),
FOREIGN KEY (LogAlarmId) REFERENCES LogAlarms(LogAlarmId) ON DELETE CASCADE,
FOREIGN KEY (SNSTopicId) REFERENCES SNSTopics(SNSTopicId) ON DELETE CASCADE,
FOREIGN KEY (UserId) REFERENCES Users(UserId) ON DELETE CASCADE,
UNIQUE (LogAlarmId, SNSTopicId, UserId)
);```
To match your description, your XRefUserLogAlarmSNSTopic is not correct.
You do not actually want to link three entities, just two: you want to relate log alarms to AWS SNS topics (which are the two values that identify that relationship), and then add a user as an attribute to that relation. Although in this case this specific attribute refers to another entity, it is logically not fundamentally different than e.g. a timestamp that stores when that relationsship was created (by that user).
The difference to your current table is the primary key/unique key: your current table allows you to add a relationship between an alarm and a topic several times if different users add them, as only (alarm, topic, user) needs to be unique, instead of (alarm, topic) being unique, and user being an attribute to that relation.
I would also consider if you want an ON DELETE CASCADE for the UserId column. While cascading for LogAlarmId and SNSTopicId makes sense, it's not obvious that you need to remove all relations when you delete the user that created them (although it of course depends on your requirements). It may be better to just set them to null. So I would propose a table like
CREATE TABLE XRefLogAlarmSNSTopic ( -- user not part of table name
LogAlarmSNSTopicId INT NOT NULL AUTO_INCREMENT,
LogAlarmId INT NOT NULL,
SNSTopicId INT NOT NULL,
UserId INT NULL, -- null
PRIMARY KEY (UserLogAlarmSNSTopicId),
FOREIGN KEY (LogAlarmId) REFERENCES LogAlarms(LogAlarmId) ON DELETE CASCADE,
FOREIGN KEY (SNSTopicId) REFERENCES SNSTopics(SNSTopicId) ON DELETE CASCADE,
FOREIGN KEY (UserId) REFERENCES Users(UserId) ON DELETE SET NULL, -- set null
UNIQUE (LogAlarmId, SNSTopicId) -- user not part of primary key candidate
)
It is obviously also possible that you want that 3-way-relationship, e.g. each user creates their own alarm-topic-relations, in which case your table would be correct, just your description would not be precise enough.

error 1215: database design with foreign key

I am trying to create three tables such as associate, manager and attendance. The attendance table should be having employee and manager details from the other two table which should enable marking the attendance. I created this SQL script. I'm not sure where I am making mistake.
CREATE TABLE associate (
id INT NOT NULL,
idmanager INT NOT NULL,
emp_id DATE NOT NULL,
emp_name VARCHAR(25) NOT NULL,
FOREIGN KEY (id) REFERENCES attendance (associate_id) ON DELETE CASCADE,
FOREIGN KEY (idmanager) REFERENCES attendance (manager_idmanager) ON DELETE CASCADE,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE manager (
id INT NOT NULL,
mgr_usr_id VARCHAR(15) NOT NULL,
mgr_name VARCHAR(25) NOT null,
KEY (id),
KEY (mgr_usr_id),
FOREIGN KEY (id) REFERENCES associate (idmanager) ON DELETE CASCADE,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE attendance (
sno INT NOT NULL,
manager_idmanager INT NOT NULL,
associate_id INT NOT NULL,
date_stamp DATETIME,
state BIT NOT NULL,
PRIMARY KEY (sno)
) ENGINE=INNODB;
Screenshot
It's an issue of ordering. For example, the first statement executed is
CREATE TABLE associate (
which references attendance. However, the attendance table has not yet been created. Switch the order so that any tables that reference other tables come last.
Alternatively, don't put the FOREIGN KEY constraints in the CREATE statements, but them at the end of your script with ALTER TABLE statements. Consider:
CREATE TABLE associate (
id INT NOT NULL,
idmanager INT NOT NULL,
emp_id DATE NOT NULL,
emp_name VARCHAR(25) NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE attendance (
sno INT NOT NULL,
manager_idmanager INT NOT NULL,
associate_id INT NOT NULL,
date_stamp DATETIME,
state BIT NOT NULL,
PRIMARY KEY (sno)
) ENGINE=INNODB;
ALTER TABLE associate ADD FOREIGN KEY (id) REFERENCES associate(id) ON DELETE CASCADE;
Edit
The above is just syntax. To model the requested problem consider orthogonality of information. You might also see/hear "normalization." The basic concept is this: have only one copy of your information. The schema should have a single point of authority for all data. For example, if a user has a birthdate, make sure you don't have an ancillary column that also stores their birthday; it's superfluous information and can lead to data errors.
In this case, what is the relationship? What must come first for the other to exist? Can an attendance be had without a manager? How about a manager without attendance? The former makes no sense. In this case then, I would actually use a third table, to form a hierarchy.
Then, consider that maybe roles change in a company. It would not behoove the DB architect to hard code roles as tables. Consider:
CREATE TABLE employee (
id INTEGER NOT NULL AUTO_INCREMENT,
name VARCHAR(25) NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE role (
id INTEGER NOT NULL AUTO_INCREMENT,
name VARCHAR(30) NOT NULL,
description VARCHAR(254) NOT NULL,
PRIMARY KEY( id ),
UNIQUE( name )
) ENGINE=INNODB;
INSERT INTO role (name, description) VALUES
('associate', 'An associate is a ...'),
('manager', 'A manager follows ...');
CREATE TABLE employee_role (
employee_id INTEGER NOT NULL,
role_id INTEGER NOT NULL,
PRIMARY KEY (employee_id, role_id),
FOREIGN KEY (idemployee_id) REFERENCES employee_id (id) ON DELETE CASCADE,
FOREIGN KEY (role_id) REFERENCES role (id) ON DELETE CASCADE
) ENGINE=INNODB;
CREATE TABLE attendance (
sno INTEGER NOT NULL,
employee_id INTEGER NOT NULL,
date_stamp DATETIME,
state BIT NOT NULL,
PRIMARY KEY (sno),
FOREIGN KEY (idemployee_id) REFERENCES employee_id (id) ON DELETE CASCADE
) ENGINE=INNODB;
From this schema, the attendance needs only one foreign key because everyone is an employee. Employee's can have multiple roles, and they can change. Further, role definitions can change without needing to resort to costly DDL statements (data definition layer changes, like ALTER TABLE), and can be modified with simple DML (data manipulation layer changes, like UPDATE TABLE). The former involves rewriting all entries in the tables, and changing schemas, while the latter involves changing individual entries.

sql code is not working in phpmyadmin using mac?

My teacher provided me with this sql code, and I logged in as root into phpmyadmin, added a database called webstore, and then tried to add this code and it's giving me errors. Is there anyone who can tell me what could be causing the errors? I am using a Mac, so I'm not sure if that makes any difference, I can give you a link to dropbox with additional information if necessary.
This is the dropbox link with the code provided (Webstore.sql): https://www.dropbox.com/sh/usfmbeyxqd2q1g5/AADoLFbsz8cL30EC76d60i40a?dl=0
Also, the zip file contains images of the errors I was receiving. PLEASE HELP!!
The SQL statement the error occurs on is
CREATE TABLE Shopping_Cart (
CustID INTEGER NOT NULL,
ProdID INTEGER NOT NULL,
NumOfItems INTEGER,
PRIMARY KEY CLUSTERED (CustID, ProdID)
CONSTRAINT FK_Cust FOREIGN KEY FK_Cat (CustID)
REFERENCES Customers (CustID)
ON DELETE RESTRICT
ON UPDATE RESTRICT,
CONSTRAINT FK_Prod FOREIGN KEY FK_Prod (ProdID)
REFERENCES Products (ProdID)
ON DELETE RESTRICT
ON UPDATE RESTRICT
);
The error reads
A comma or closing bracket was expected. (near "CONSTRAINT" at position 153)
Unexpected beginning of statement. (near "CustID" at position 192)
Unrecognised statement type. (near "REFERENCES" at position 206)
Your PRIMARY KEY line needs a comma after it before the CONSTRAINT.
CREATE TABLE Shopping_Cart (
CustID INTEGER NOT NULL,
ProdID INTEGER NOT NULL,
NumOfItems INTEGER,
PRIMARY KEY CLUSTERED (CustID, ProdID),
CONSTRAINT FK_Cust FOREIGN KEY FK_Cat (CustID)
REFERENCES Customers (CustID)
ON DELETE RESTRICT
ON UPDATE RESTRICT,
CONSTRAINT FK_Prod FOREIGN KEY FK_Prod (ProdID)
REFERENCES Products (ProdID)
ON DELETE RESTRICT
ON UPDATE RESTRICT
);
Edit
It turns out there were a lot of problems with the SQL. The tables were created in the wrong order and the data types were wrong. Here is a rewritten version that I have tested out:
DROP DATABASE IF EXISTS WebStore;
CREATE DATABASE WebStore;
USE WebStore;
CREATE TABLE Categories (
CatID INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
Name VARCHAR(20) NOT NULL,
Descr VARCHAR(120) NOT NULL,
IconURL VARCHAR(64) NOT NULL,
PRIMARY KEY (CatID)
);
CREATE TABLE Products (
ProdID INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
Name VARCHAR(20) NOT NULL,
Category INTEGER UNSIGNED,
Descr VARCHAR(120) NOT NULL,
Price FLOAT NOT NULL,
Stock INTEGER UNSIGNED NOT NULL,
IconURL VARCHAR(64) NOT NULL,
PRIMARY KEY (ProdID),
CONSTRAINT FK_Cat FOREIGN KEY FK_Cat (Category)
REFERENCES Categories (CatID)
ON DELETE RESTRICT
ON UPDATE RESTRICT
);
INSERT INTO Categories VALUES(null,"Laptops","Small computers you can carry","http://localhost/images/laptop.jpg");
SET #laptops := LAST_INSERT_ID();
INSERT INTO Categories VALUES(null,"Desktops","Big computers you cannot carry","http://localhost/images/desktop.jpg");
SET #desktops := LAST_INSERT_ID();
INSERT INTO Categories VALUES(null,"Tablets"," Flat things you lose frequently","http://localhost/images/tablet.jpg");
SET #tablets := LAST_INSERT_ID();
INSERT INTO Products VALUES(null,"DULL 1200",#desktops,"A big dull machine",1290.99,23,"http://localhost/images/dull1200.jpg");
INSERT INTO Products VALUES(null,"8P Totalo",#desktops,"Almost as big as the DULL",990.99,2,"http://localhost/images/8ptotalo.jpg");
INSERT INTO Products VALUES(null,"LaNuveau Bingster",#desktops,"Comes in blue and red",690.99,12,"http://localhost/images/lanuveaubingster.jpg");
INSERT INTO Products VALUES(null,"DULL 122",#laptops,"Small, portable and useless",422.99,4,"http://localhost/images/dull122.jpg");
INSERT INTO Products VALUES(null,"8P Tootsie",#laptops,"Sticky and too heavy",559.99,12,"http://localhost/images/8ptootsie.jpg");
INSERT INTO Products VALUES(null,"LaNuveau Shoobie XT",#laptops,"Weighs a ton but looks sharp",1690.99,122,"http://localhost/images/lanuveaushoobiext.jpg");
INSERT INTO Products VALUES(null,"Motor Roller 12",#tablets,"The only one with a oval screen",422.99,4,"http://localhost/images/mr12.jpg");
INSERT INTO Products VALUES(null,"SamSings OffKey",#tablets,"Needs duct tape to run",559.99,2,"http://localhost/images/samsingsOK.jpg");
INSERT INTO Products VALUES(null,"jPet 12",#tablets,"The first that kinda sorta works",16290.99,722,"http://localhost/images/jpet12.jpg");
CREATE TABLE Customers (
CustID INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
FirstName VARCHAR(40) NOT NULL,
LastName VARCHAR(40) NOT NULL,
Address VARCHAR(60) NOT NULL,
City VARCHAR(40) NOT NULL,
State VARCHAR(20) NOT NULL,
Zip VARCHAR(5) NOT NULL,
PRIMARY KEY (CustID)
);
INSERT INTO Customers VALUES(null,"Gerald","Bostock","1234 TAAB Drive","St. Cleve","FL","12345");
INSERT INTO Customers VALUES(null,"Suzy","Creamcheese","8722 Zappa Road","Paris","TX","75460");
CREATE TABLE Shopping_Cart (
CustID INTEGER UNSIGNED NOT NULL,
ProdID INTEGER UNSIGNED NOT NULL,
NumOfItems INTEGER,
PRIMARY KEY CLUSTERED (CustID, ProdID),
CONSTRAINT FK_Cust FOREIGN KEY FK_Cat (CustID)
REFERENCES Customers (CustID)
ON DELETE RESTRICT
ON UPDATE RESTRICT,
CONSTRAINT FK_Prod FOREIGN KEY FK_Prod (ProdID)
REFERENCES Products (ProdID)
ON DELETE RESTRICT
ON UPDATE RESTRICT
);
INSERT INTO Shopping_Cart VALUES("1","4","2");
INSERT INTO Shopping_Cart VALUES("1","9","1");

SQL nested query returns nothing

I am a beginner in SQL and am having difficulty understanding the logic query. In this particular problem, I am trying to find the Track that was purchased in California.
Here are the tables.
CREATE TABLE [InvoiceLine]
(
[InvoiceLineId] INTEGER NOT NULL,
[InvoiceId] INTEGER NOT NULL,
[TrackId] INTEGER NOT NULL,
[UnitPrice] NUMERIC(10,2) NOT NULL,
[Quantity] INTEGER NOT NULL,
CONSTRAINT [PK_InvoiceLine] PRIMARY KEY ([InvoiceLineId]),
FOREIGN KEY ([InvoiceId]) REFERENCES [Invoice] ([InvoiceId])
ON DELETE NO ACTION ON UPDATE NO ACTION,
FOREIGN KEY ([TrackId]) REFERENCES [Track] ([TrackId])
ON DELETE NO ACTION ON UPDATE NO ACTION
);
CREATE TABLE [Invoice]
(
[InvoiceId] INTEGER NOT NULL,
[CustomerId] INTEGER NOT NULL,
[InvoiceDate] DATETIME NOT NULL,
[BillingAddress] NVARCHAR(70),
[BillingCity] NVARCHAR(40),
[BillingState] NVARCHAR(40),
[BillingCountry] NVARCHAR(40),
[BillingPostalCode] NVARCHAR(10),
[Total] NUMERIC(10,2) NOT NULL,
CONSTRAINT [PK_Invoice] PRIMARY KEY ([InvoiceId]),
FOREIGN KEY ([CustomerId]) REFERENCES [Customer] ([CustomerId])
ON DELETE NO ACTION ON UPDATE NO ACTION
);
CREATE TABLE [Track]
(
[TrackId] INTEGER NOT NULL,
[Name] NVARCHAR(200) NOT NULL,
[AlbumId] INTEGER,
[MediaTypeId] INTEGER NOT NULL,
[GenreId] INTEGER,
[Composer] NVARCHAR(220),
[Milliseconds] INTEGER NOT NULL,
[Bytes] INTEGER,
[UnitPrice] NUMERIC(10,2) NOT NULL,
CONSTRAINT [PK_Track] PRIMARY KEY ([TrackId]),
FOREIGN KEY ([AlbumId]) REFERENCES [Album] ([AlbumId])
ON DELETE NO ACTION ON UPDATE NO ACTION,
FOREIGN KEY ([GenreId]) REFERENCES [Genre] ([GenreId])
ON DELETE NO ACTION ON UPDATE NO ACTION,
FOREIGN KEY ([MediaTypeId]) REFERENCES [MediaType] ([MediaTypeId])
ON DELETE NO ACTION ON UPDATE NO ACTION
);
Here is what I've tried.
SELECT T.name
FROM Track T, InvoiceLine L
WHERE T.trackid=L.trackid AND
L.invoiceid IN (SELECT I.invoiceid
FROM Invoice I
WHERE I.billingcity="California");
The query returns nothing. What is wrong with the logic?
SELECT
T.name
FROM Track T
INNER JOIN InvoiceLine L ON T.trackid = L.trackid
INNER JOIN invoice I ON L.InvoiceId = I.InvoiceId
WHERE I.BillingState = 'California'
Track joins to InvoiceLine which joins to Invoice
Please do NOT use the ancient way of joining through the where clause. The simplest trick for this is to disallow any commas between table e.g. note the comma in: FROM Track T, InvoiceLine L - avoid those.
I assume you want the state of California held in BillingState not a city of that name (if one exists).

Trigger in MYSQL that delete

I have posted this code in another threat, but this question is slightly different. I have to make a trigger. The question sounds like this:
"Create a trigger that removes the season if unused whenever
information about when and who produces a product is deleted (i.e.,
whenever a record is removed from the 'Produces' table, check if there
are other records about product being produced for the same season, if
not, remove also the corresponding record from the season table)"
My MYSQL code:
the MYSQL code is here:
CREATE TABLE IF NOT EXISTS Dvds(
Serial integer NOT NULL,
Name varchar(50),
Year integer,
Genre varchar(50),
Price integer,
PRIMARY KEY (Serial));
CREATE TABLE IF NOT EXISTS Shops(
Id integer NOT NULL,
Name varchar(50),
Address varchar(50),
PRIMARY KEY (Id));
CREATE TABLE IF NOT EXISTS Customers(
CNo integer NOT NULL,
AccNo integer,
Time varchar(50),
PRIMARY KEY (CNo));
CREATE TABLE IF NOT EXISTS ContactPersons(
Id integer NOT NULL,
Name varchar(50),
Phone integer,
PRIMARY KEY (Id));
CREATE TABLE IF NOT EXISTS Seasons(
StartDate date NOT NULL,
EndDate date NOT NULL,
PRIMARY KEY (StartDate,EndDate));
CREATE TABLE IF NOT EXISTS WebShops(
Id integer NOT NULL,
Url varchar(50),
FOREIGN KEY (Id) REFERENCES Shops (Id),
PRIMARY KEY (Id));
CREATE TABLE IF NOT EXISTS Producer(
Id integer NOT NULL,
Address varchar(50),
Name varchar(50),
PRIMARY KEY (Id));
CREATE TABLE IF NOT EXISTS Sold(
Id integer NOT NULL,
CNo integer NOT NULL,
Serial integer NOT NULL,
FOREIGN KEY (Id) REFERENCES Shops (Id),
FOREIGN KEY (CNo) REFERENCES Customers (CNo),
FOREIGN KEY (Serial) REFERENCES Dvds (Serial),
PRIMARY KEY (Id,CNo,Serial));
CREATE TABLE IF NOT EXISTS Has(
Id integer NOT NULL,
Serial integer NOT NULL,
FOREIGN KEY (Id) REFERENCES Shops (Id),
FOREIGN KEY (Serial) REFERENCES Dvds (Serial),
PRIMARY KEY (Id,Serial));
CREATE TABLE IF NOT EXISTS Has2(
Serial integer NOT NULL,
Producer_Id integer NOT NULL,
StartDate date NOT NULL,
EndDate date NOT NULL,
ContactPersons_Id integer NOT NULL,
FOREIGN KEY (Serial) REFERENCES Dvds (Serial),
FOREIGN KEY ( Producer_Id) REFERENCES Producer (Id),
FOREIGN KEY (StartDate) REFERENCES Seasons (StartDate),
FOREIGN KEY (EndDate) REFERENCES Seasons (EndDate),
FOREIGN KEY (ContactPersons_Id) REFERENCES ContactPersons (Id),
PRIMARY KEY (Serial,Producer_Id,StartDate,EndDate,ContactPersons_Id));
The trigger:
CREATE TRIGGER `Seasons_before_delete`
AFTER DELETE ON `Seasons`
FOR EACH ROW
BEGIN
DELETE FROM seasonstart
WHERE seasonstart.???????
DELETE FROM seasonend
WHERE seasonend.??????
END
but I really don't know. My teacher told me that I could use IF , ELSEIF, GOTOEND? But am i on the right track? I'm really blank right now what to do, so hope someone have a suggestion, what I could do to solve this?
In a trigger you have 2 virtual tables.
NEW and OLD.
Obviously in a create trigger there is no old and in a delete trigger there is no new.
So if you want to use the data of the table where the change happened (the table the trigger is attached to) you use those two tables.
Because this is a delete trigger you'll need to use the old table.
So your trigger will look something like this:
CREATE TRIGGER `Seasons_before_delete` AFTER DELETE ON `Seasons`
FOR EACH ROW
BEGIN
DELETE FROM seasonstart
WHERE seasonstart.seasonID = old.ID
DELETE FROM seasonend
WHERE seasonend.seasonID = old.ID
END
Note that it makes little sense to call a AFTER DELETE trigger "something_something_BEFORE" :-).
Further note that I have no idea why you need an IF in this trigger, the where in the delete statement already takes care of that.