gpt4 book ai didi

mysql - 获取一些行和总数的存储过程

转载 作者:行者123 更新时间:2023-11-29 06:42:34 25 4
gpt4 key购买 nike

我是 sql 新手,所以我需要你的帮助!我需要一个存储过程来获取一定数量的文章,其中有一些偏移量和它们的总数来进行分页......这是正确的代码还是有更好的方法?将执行多少查询,ctid 1 个,总计 1 个,内容数据 1 个??

DELIMITER $$
CREATE PROCEDURE `getArticles`(`offset` INT, `count` INT)
BEGIN
DECLARE ctid, total INT;
SET ctid = (SELECT id FROM content_types WHERE name='article');
SET total = (SELECT COUNT(*) FROM content WHERE content_type = ctid);
SELECT *, total FROM content
WHERE content_type = ctid
LIMIT count
OFFSET offset;
END $$
DELIMITER ;

最佳答案

您可以尝试利用 SQL_CALC_FOUND_ROWS 选项和 FOUND_ROWS()功能

SQL_CALC_FOUND_ROWS and FOUND_ROWS() can be useful in situations when you want to restrict the number of rows that a query returns, but also determine the number of rows in the full result set without running the query again. An example is a Web script that presents a paged display containing links to the pages that show other sections of a search result. Using FOUND_ROWS() enables you to determine how many other pages are needed for the rest of the result.

话虽如此,您的程序可能看起来像

DELIMITER $$
CREATE PROCEDURE get_articles(IN _offset INT, IN _count INT, OUT _total INT)
BEGIN
SELECT SQL_CALC_FOUND_ROWS *
FROM content c JOIN content_types t
ON c.content_type = t.id
WHERE t.name = 'article'
LIMIT _offset, _count;
SET _total = FOUND_ROWS();
END$$
DELIMITER ;

示例用法:

SET @total = 0;
CALL get_articles(0, 3, @total);
SELECT @total;

这是 SQLFiddle 演示

关于mysql - 获取一些行和总数的存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20545942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com