2016-06-09 82 views
0

我試圖編寫觸發器來使我的故事數據庫的字索引無效。然而,我似乎無法弄清楚在索引操作過程中如何停止觸發器再次觸發。我知道我需要放置一條if語句來停止更新,但我似乎無法弄清楚它應該是什麼樣子。更新後觸發無效緩存

CREATE TRIGGER trMarkStoryForReindex BEFORE UPDATE ON Chapters 
    FOR EACH ROW BEGIN 

    -- any update to any chapter invalidates the index for the whole story 
    -- we could just periodically flush the story index, but this way is 
    -- better. 
    SET New.isIndexed = FALSE; 
    -- delete the index for that story 
    -- It will get rebuilt in at most 15 minutes 
    DELETE FROM freq WHERE storyid = NEW.StoryId; 
END; 

我基本上只想觸發器只有在觸發器的update語句中沒有設置isIndexed時才觸發。

我的數據模型看起來像這樣:

  • ID
  • isIndexed
  • StoryId

頻率

  • storyid
+0

有沒有'在'Chapters'表StoryId'場。你的意思是:'從freq中刪除where storyid = new.id'? – Barranka

+0

@Barranka章節表中有一個StoryId字段。我只是忘記在問題中加入這個問題。 – HSchmale

+0

請問您可以發佈一個數據示例或[SQL小提琴](http://sqlfiddle.com)示例? – Barranka

回答

0

這裏是我的解決方案建議。我已經在SQL小提琴進行了測試,它似乎工作:

-- Database setup 
create table chapters (
    id int unsigned not null auto_increment primary key, 
    isIndexed boolean default false, 
    storyId int not null, 
    index idx_storyId(storyId) 
); 

create table freq (
    word varchar(50), 
    storyId int not null, 
    index idx_storyId(storyId) 
); 

delimiter // 
create trigger bi_chapters before update on chapters 
for each row 
begin 
    if new.isIndexed = false then 
    delete from freq where storyId = new.storyId; 
    end if; 
end // 
delimiter ; 

insert into freq(word, storyId) 
values ('one', 1), ('two', 1), ('three', 2); 

insert into chapters(isIndexed, storyId) 
values (true, 1), (true, 2); 

當你(更新chapters之前)選擇freq的值,你會得到:

select * from chapters; 

| id | isIndexed | storyId | 
|----|-----------|---------| 
| 1 |  false |  1 | 
| 2 |  true |  2 | 

select * from freq; 

| word | storyId | 
|-------|---------| 
| one |  1 | 
| two |  1 | 
| three |  2 | 

現在,做一個update到章節,從selectfreq再次:

update chapters 
    set isIndexed = false 
    where storyId = 1; 
select * from freq; 

| word | storyId | 
|-------|---------| 
| three |  2 | 

我做的唯一的修改是if塊檢查新行是否更新爲false。如果我已經正確理解你的問題,這將做你所需要的。