1

我在另一个威胁中发布了这段代码,但这个问题略有不同。我必须做一个触发器。这个问题听起来像这样:

“创建一个触发器,在删除有关何时和谁生产产品的信息时删除未使用的季节(即,每当从“生产”表中删除记录时,检查是否还有其他有关同一季节生产的产品的记录, 如果没有, 从季节表中删除相应的记录)"

我的MYSQL代码:

MYSQL 代码在这里:

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));

触发:

CREATE TRIGGER `Seasons_before_delete` 
    AFTER DELETE ON `Seasons`
    FOR EACH ROW 
    BEGIN
    DELETE FROM seasonstart
    WHERE seasonstart.???????
    DELETE FROM seasonend
    WHERE seasonend.??????
    END

但我真的不知道。我的老师告诉我,我可以使用IF, ELSEIF, GOTOEND? 但我在正确的轨道上吗?我现在真的很空白该怎么办,所以希望有人有建议,我能做些什么来解决这个问题?

4

1 回答 1

2

在触发器中,您有 2 个虚拟表。

NEWOLD

显然在create触发器中没有old,在delete触发器中没有new。因此,如果您想使用发生更改的表(触发器附加到的表)的数据,您可以使用这两个表。

因为这是一个delete触发器,所以您需要使用该old表。

所以你的触发器看起来像这样:

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

请注意,调用AFTER DELETE触发器“something_something_BEFORE”是没有意义的 :-)。

进一步注意,我不知道为什么你需要IF在这个触发器中,where在 delete 语句中已经解决了这个问题。

于 2012-12-06T17:37:19.217 回答