触发复合键并更新另一列

时间:2013-10-29 19:13:29

标签: mysql sql

我有两个表:threadsthreadreply

threads有一个复合主键(thread_id,reply_id)

当我向threadreply插入新行时,我需要:

  • 通过向上一个值添加+1来更新我的专栏threads.reply_count;以及

  • 通过向threadreply MAX(reply_id)添加+1,将数据插入thread_id

使用以下触发器,我可以向reply_id添加+ 1,但无法更新我的reply_count

CREATE TRIGGER addone BEFORE INSERT ON threadreply
FOR EACH ROW BEGIN
    SET NEW.reply_id = (
        SELECT IFNULL(
            (
                SELECT MAX(reply_id) + 1
                FROM   threadreply
                WHERE  thread_id = NEW.thread_id
            ),
            1
        )
    );
END

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

我假设问题中存在拼写错误,而(thread_id,reply_id)表中存在复合键threadreply,而不是threads表中。

触发器可能如下所示:

CREATE TRIGGER addone BEFORE INSERT ON threadreply
FOR EACH ROW BEGIN
    SET NEW.reply_id = (
        SELECT IFNULL(
            (
                SELECT MAX(reply_id) + 1
                FROM   threadreply
                WHERE  thread_id = NEW.thread_id
            ), 1
        )
    );
    UPDATE threads SET reply_count = reply_count + 1
    WHERE thread_id = NEW.thread_id;
END
/

看看这个演示: - > http://www.sqlfiddle.com/#!2/1e7bb/2

触发器和插入语句位于schema窗口的左侧,下面显示了演示的结果。