首页 > 解决方案 > SQL“插入触发器后”抱怨字段列表中的未知列“currentId”,即游标

问题描述

我有 2 张桌子。

create table comments (
    id int auto_increment primary key,
    task_id int not null,
    foreign key fk_comment_task(task_id) references tasks(id),
    user int not null,
    foreign key fk_comment_user(user) references users(id),
    comment varchar(1000) not null,
    comment_date date not null,
    viewed tinyint(1) not null default 0,
    deleted tinyint(1) not null default 0   
) engine = InnoDB;

第二个:

create table viewed_comments (
    id int auto_increment primary key,
    comment int not null,
    foreign key fk_viewed_comment(comment) references comments(id),
    viewer int not null,
    foreign key fk_viewed_viewer(viewer) references users(id),
    unread tinyint(1) not null default 0,
    deleted tinyint(1) not null default 0
) engine = InnoDB;

我想创建一个触发器,当评论插入到“评论”表中时,“viewed_comments”表会为除提交评论的用户之外的所有用户创建该评论的行。

目前,我有一个触发器:

delimiter |
create trigger ins_views after insert on comments 
for each row 
    begin
        DECLARE finished INT DEFAULT 0;
        DECLARE id INT DEFAULT 0;

        DECLARE currentId CURSOR FOR SELECT id FROM users WHERE id != NEW.user;

        DECLARE CONTINUE HANDLER 
            FOR NOT FOUND SET finished = 1;

        OPEN currentId;

        update_views_loop: LOOP
            FETCH currentId INTO id;
            IF finished = 1 THEN LEAVE update_views_loop;

            END IF;
            INSERT INTO viewed_comments (comment, viewer) VALUES (NEW.id, currentId);   

        END LOOP update_views_loop;

     CLOSE currentId;

    END;
|

delimiter ;

当我插入诸如“插入评论(task_id、user、comment、comment_date)值(24、4、'test'、'2018-3-5')之类的内容时;例如,我得到以下响应。错误 1054 (42S22):“字段列表”中的未知列“currentId”是光标。我该如何解决?

标签: mysqlsql

解决方案


 INSERT INTO viewed_comments (comment, viewer) VALUES (NEW.id, id);

因为您将值读入变量 id。使用此值而不是光标。

 FETCH currentId INTO id;

推荐阅读