Question

I'm new in sql, so i need your help! I need a stored procedure to get a certain number of articles with some offset and total number of them to make pagination... is this a correct code or there is a better way? How much queries will be executed, 1 for ctid, 1 for total and 1 for content data??

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 ;
Was it helpful?

Solution

You can try to leverage SQL_CALC_FOUND_ROWS option and FOUND_ROWS() function

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.

That being said your procedure might look like

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 ;

Sample usage:

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

Here is SQLFiddle demo

OTHER TIPS

I guess your lookin a query like this. Try to do everything in the same query, if it doesn't get too complex.

SELECT c.*, 
      (SELECT COUNT(*) FROM content AS c1 WHERE c1.content_type = ct.id) AS total  
  FROM content AS c 
  INNER JOIN content_type AS ct ON c.content_type = ct.id
WHERE ct.name = 'article'
  LIMIT offset, count;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top