2016-06-09 84 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。如果我已经正确理解你的问题,这将做你所需要的。