在Python中使用MySQL存储过程的SQL_CALC_FOUND_ROWS

1 投票
1 回答
1058 浏览
提问于 2025-04-17 02:05

看看这个存储过程

-- --------------------------------------------------------------------------------
-- Routine DDL
-- --------------------------------------------------------------------------------
DELIMITER $$

CREATE DEFINER=`root`@`localhost` PROCEDURE `get_followers`(in _user_id int,in _topic_id int,in _type int)
MAIN:BEGIN

SELECT SQL_CALC_FOUND_ROWS follow.user_id
            -- COUNT(follow.user_id) AS _topic_idcount
FROM
    follow
WHERE 
    follow.followee_user_id = _user_id
    AND (topic_id = _topic_id OR topic_id = 0)
GROUP BY follow.user_id;
SELECT FOUND_ROWS() AS count;

END

当我在 MySQL Workbench 中测试调用这个存储过程时,它返回的结果是我预期的数量。

但是,当我执行 Python 代码并输出这个查询的 JSON 结果时,得到的结果却是这样的。

[{"user_id": 3}, {"user_id": 4}, {"user_id": 5}]

在我看来,当我从 Python 代码调用存储过程时,它没有考虑到 SELECT FOUND_ROWS() AS count; 这个语句。

results = execute_sp("get_followers", [user_id, topic_id, type])

这里的 execut 是我自定义的函数。

def execute_sp( sp_name, paramaters ):
    #helper method to run sp's and return results
    db = Db()
    cursor = db.cursor()
    cursor.callproc(sp_name,paramaters)
    results = cursor.fetchallDict()
    cursor.close()
    return results

请帮我解决这个问题.....

1 个回答

1

你得试试看这个方法是否有效——我现在没法测试...

在mysqldb看来,results = cursor.fetchallDict() 只返回了第一个结果集。也就是说,它只拿到了第一次查询(SELECT)的结果。你可以试着加一个 nextset() 的调用,像这样:

def execute_sp( sp_name, paramaters ):
    #helper method to run sp's and return results
    db = Db()
    cursor = db.cursor()
    cursor.callproc(sp_name,paramaters)
    cursor.nextset() #Need the second result set in the proc
    results = cursor.fetchallDict()
    cursor.close()
    return results

如果这个方法不行,告诉我一声。

撰写回答