mysql - 具有子查询的 PROCEDURE 中的 CURSOR

标签 mysql sql cursor

我在 MySQL 中有这个过程(其中的一部分)

DECLARE num_rows INT(11) DEFAULT NULL;
DECLARE insert_result INT(11) DEFAULT NULL;

DECLARE var_user_id INT DEFAULT NULL;
DECLARE user_that_posted_this_post INT DEFAULT NULL;
DECLARE arg_in_group_id INT DEFAULT NULL;
DECLARE how_many_comments INT DEFAULT 0;

/* Cursor 1 (posts) */
DECLARE done INT DEFAULT 0;
DECLARE c1 CURSOR FOR 
    SELECT user_id 
    FROM user_rights 
    WHERE user_rights.right = 101 AND 
    user_rights.group_id  = 
    (
        SELECT 
        posted_in
        FROM posts
        WHERE
        id = arg_post_id
    )
    ORDER BY user_id DESC;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

/* See how many comments has this post */
SELECT count(id) FROM  comments_posts WHERE posted_in = arg_post_id INTO how_many_comments;

/* Fetch the autor of this post and the group_id */
SELECT posted_by,posted_in FROM posts WHERE id = arg_post_id INTO user_that_posted_this_post,arg_in_group_id;

IF arg_post_id IS NULL OR arg_post_id = ''
THEN
    SELECT '0' AS response;
ELSE
    DELETE FROM posts WHERE id = arg_post_id;
END IF;

/* Increment the notifications for every afected user */
INSERT INTO t VALUES(0);
OPEN c1;
read_loop: LOOP
    FETCH c1 INTO var_user_id;
        IF done THEN
            LEAVE read_loop;
        ELSE
            INSERT INTO t VALUES(var_user_id);
        END IF;
END LOOP;
CLOSE c1;

我发生了一些有线的事情(光标没有取任何值),例如这个查询

SELECT user_id 
FROM user_rights 
WHERE user_rights.right = 101 AND 
user_rights.group_id  = 
(
    SELECT 
    posted_in
    FROM posts
    WHERE
    id = arg_post_id
)

返回已发布帖子的组中拥有 101(阅读)权限的所有用户。结果在sql中完美运行,例如

SELECT user_id 
FROM user_rights 
WHERE user_rights.right = 101 AND 
user_rights.group_id  = 
(
    SELECT 
    posted_in
    FROM posts
    WHERE
    id = 247
)

RESULT
user_id
1
3
2
16
17
20
19  

但是当我尝试从 CURSOR 输出时

/* Increment the notifications for every afected user */
INSERT INTO t VALUES(0);
OPEN c1;
read_loop: LOOP
    FETCH c1 INTO var_user_id;
        IF done THEN
            LEAVE read_loop;
        ELSE
            INSERT INTO t VALUES(var_user_id);
        END IF;
END LOOP;
CLOSE c1;

它不起作用...它只在 t 表中写入“0”,这是为什么?我不能在游标中使用子查询?

最佳答案

它不起作用,因为游标是不敏感的,这意味着它指向真实数据。它不适用于这样的子查询:

DECLARE c1 CURSOR FOR 
    SELECT user_id 
    FROM user_rights 
    WHERE user_rights.right = 101 AND 
    user_rights.group_id  = 
    (
        SELECT 
        posted_in
        FROM posts
        WHERE
        id = arg_post_id
    )
    ORDER BY user_id DESC;

关于mysql - 具有子查询的 PROCEDURE 中的 CURSOR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12402090/

相关文章:

c# - 将控制台光标设置为粗/细

mysql - 如何将列合并为一行

php - 如何编写 PHP 按钮来从数据库中选择行并运行 python 代码

mysql - 将 MySQL 子查询的结果保存到 TEMPORARY TABLE 中的开销(而不是复制子查询)?

mysql - Join WithWhere 子句 - 嵌套连接/Where?

asp.net - 使用@@identity检索PK

mysql - 使用多个选择器从 SQL 中的一组中选择一行

mysql - 如何在Python和MySQL中更优雅地进行这种查找?

html - 为什么我的自定义光标的位置偏离了?

mysql - DB 关系(对于任何 ORM 都很优雅)