0

我有两张桌子:threadsthreadreply

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

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

  • 通过在前一个值上添加 +1 来更新我的列threads.reply_count;和

  • threadreply通过将 +1 添加到MAX(reply_id)with same来插入数据thread_id

使用以下触发器,我能够将 +1 添加到 my reply_id,但无法更新 my 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

我该如何解决这个问题?

4

1 回答 1

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,下面是演示的结果。

于 2013-11-02T08:39:57.897 回答