sql触发两个表不为空

时间:2018-04-13 16:33:18

标签: mysql sql jsp triggers

CREATE TRIGGER bookAvailDelete after delete on Auction
for each row
Begin
if (Select count(OLD.isbn) from Auction a > 0)
update Book b
set available =false
where OLD.isbn = isbn
;

我有两张桌子,拍卖和书。拍卖有isbn关键,参考Book isbn主键。许多拍卖可以指向同一本书,所以我希望这个触发器检查每次拍卖删除,看看它是否是该书的最后一次拍卖isbn。如果是,则将Book中的“available”键设置为false。

3 个答案:

答案 0 :(得分:0)

请在下面编译测试。使用变量作为计数,如果最后也将结束。

delimiter //
CREATE TRIGGER bookAvailDelete after delete on Auction
for each row
Begin
DECLARE updatecount INT;
set updatecount = ( Select count(*) from Auction a where a.isbn = OLD.isbn);
if updatecount > 0 then
update Book b
set b.available =false
where b.isbn = OLD.isbn;
end if;
End;//

答案 1 :(得分:0)

通常情况下,除非出现性能原因,否则您只需动态计算(而不是存储),查询如下:

SELECT b.*
   , EXISTS(SELECT * FROM Auction a WHERE a.isbn = b.isbn) AS available
FROM Book b

或(我的首选格式):

SELECT b.*, (a.isbn IS NOT NULL) AS available
FROM Book b
LEFT JOIN (SELECT DISTINCT isbn FROM Auction) AS a ON b.isbn = a.isbn
;

答案 2 :(得分:0)

假设可用的是int:

drop trigger bookAvailDelete;

DELIMITER //
CREATE TRIGGER bookAvailDelete after delete on Auction
    for each row begin
        if NOT EXISTS(Select * from Auction where isbn = old.isbn)
        then
            update Book b set b.available = 0 where b.isbn = old.isbn;
        end if; 
    end;