How to count and limit record in a single query in MYSQL?

后端 未结 5 2041
刺人心
刺人心 2020-12-14 09:46

I am searching for records in a table as follows:

SELECT Id, Name FROM my_table WHERE Name LIKE \'%prashant%\' LIMIT 0, 10;

Now, I am addin

5条回答
  •  渐次进展
    2020-12-14 10:03

    This is for others with the same need (considering it's been 3 years from the time of this question).

    I had a similar issue and I didn't want to create 2 queries. So what I did was to create an additional column for the total number and moved the LIMIT and OFFSET clauses at the end:

    SELECT SQL_CALC_FOUND_ROWS * FROM (
        SELECT `id`, `name`
        FROM `my_table`
        WHERE `name` LIKE '%prashant%'
    ) res,
    (SELECT /*CEIL(FOUND_ROWS()/10) AS 'pages',*/ FOUND_ROWS() AS 'total') tot
    LIMIT 0, 10
    

    So the result is something like

    | id  |      name      | total |
    +-----+----------------+-------+
    |  1  | Jason Prashant |  124  |
    |  2  | Bob Prashant   |  124  |
    |  3  | Sam Prashant   |  124  |
    |  4  | etc. prashant  |  124  |
    

    and I think this solution has no disadvantage in timing because it fetches the result only once, and then uses the already calculated row count for the additional column.

提交回复
热议问题