How to count all rows when using SELECT with LIMIT in MySQL query?

前端 未结 5 1403
一整个雨季
一整个雨季 2020-11-27 05:47

I\'ve got a mysql query like this:

SELECT A.ID, A.NAME, B.ID, B.NAME
FROM table1 A
JOIN table2 B ON ( A.ID = B.TABLE1_ID )
WHERE
    cond1, cond2, ..., condN         


        
5条回答
  •  臣服心动
    2020-11-27 06:38

    'tis 4 years since the last answer, but this is how I resolved the problem. Although SaltLake's answer produced an error for me, it did lead me to the correct answer.

    SELECT SQL_CALC_FOUND_ROWS * FROM wholedatabase LIMIT 0,10 UNION 
    SELECT 'TotalRows', FOUND_ROWS(), NULL, NULL, NULL, NULL
    ORDER BY IssueDate, VolumeNo 
    

    The UNION part is very important, because it tags your desired answer (Total number of rows) that is retrieved in the SECOND Select result onto the FIRST Select results.

    Another very important point is that, because a UNION is taking place, both tables must have the same number of columns in them. This usually means that you have to pad the SECOND Select with the all-important FOUND_ROWS() value, and then lots of NULL values.

    The final result will be one command that will return 11 rows of information, with one of these rows containing the total number of rows. Obviously, you will need to exclude the additional TotalRows row when you come to using the result.

提交回复
热议问题