MySQL 光标在一个变量中有多个值?

MySQL cursor multiple values in a variable?

我在触发器中有这样的东西:

OPEN cursor_things;
        loop_through_rows : LOOP
            FETCH cursor_things INTO things;

            IF done THEN
                LEAVE loop_through_rows;
            END IF ;
        END LOOP;
 CLOSE cursor_things;

其中 SQL 是:

DECLARE cursor_things CURSOR FOR
    SELECT id
    FROM things
    WHERE thing.id = OLD.id;

问题是 SQL returns 多行和变量被覆盖。有没有办法在变量中存储多个值?或者,有更好的方法吗?

编辑: 游标可能不是最佳解决方案。最初我只是在尝试一个变量:

如果我们有书籍和作者table。作者写了很多书。 我想从书中获取所有 id table

我只想能够做到这一点:

 INSERT INTO changes (`action`, `data`)
    VALUES ('changed',
            JSON_OBJECT(
                    'author', NEW.author,
                    'book_ids', #how do I get these ids
            )
  );

所以也许是这样的:

SET bookIds = (SELECT JSON_ARRAYAGG( book_id) from books WHERE author_id = 13);

再详细一点,我真正需要的是:

JSON_OBJECT(
                    'author', NEW.author,
                    'books', [
                    [related book1 id, related book1 type],
                    [related book2 id, related book2 type]
            )

郑重声明,不,不可能在一个标量变量中存储多个值。

我确实认为有更好的方法来完成您描述的内容。大多数在 MySQL 过程中使用 CURSOR 的情况都可以在单个查询中完成,无需循环。例如:

INSERT INTO changes (`action`, `data`)
SELECT 'changed', JSON_OBJECT()
  'author', NEW.author,
  'books', JSON_ARRAYAGG(
             JSON_OBJECT(
               'book_id', id,
               'book_type', book_type
             )
           )
FROM books
WHERE author_id = NEW.author;