开发者

Help counting total number of rows

I have the following type of query:

SELECT * FROM TABLE
GROUP BY Table.Table_ID
LIMIT 10

I want to know how many rows would be selected if that开发者_运维知识库 LIMIT 10 weren't there. I can't simply select COUNT(Table_ID) because I group by that, so it will give 1 in every row for that.


Clearly described in the manual:

SQL_CALC_FOUND_ROWS tells MySQL to calculate how many rows there would be in the result set, disregarding any LIMIT clause. The number of rows can then be retrieved with SELECT FOUND_ROWS(). See Section 11.13, “Information Functions”.

If you follow the link to Section 11.13, there's then an example:

FOUND_ROWS()

A SELECT statement may include a LIMIT clause to restrict the number of rows the server returns to the client. In some cases, it is desirable to know how many rows the statement would have returned without the LIMIT, but without running the statement again. To obtain this row count, include a SQL_CALC_FOUND_ROWS option in the SELECT statement, and then invoke FOUND_ROWS() afterward:

mysql> SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name
    -> WHERE id > 100 LIMIT 10;
mysql> SELECT FOUND_ROWS();

The second SELECT returns a number indicating how many rows the first SELECT would have returned had it been written without the LIMIT clause.

In the absence of the SQL_CALC_FOUND_ROWS option in the most recent successful SELECT statement, FOUND_ROWS() returns the number of rows in the result set returned by that statement. If the statement includes a LIMIT clause, FOUND_ROWS() returns the number of rows up to the limit. For example, FOUND_ROWS() returns 10 or 60, respectively, if the statement includes LIMIT 10 or LIMIT 50, 10.

Please, use the documentation as your first port of call.


SELECT COUNT(DISTINCT TABLE_ID) FROM TABLE


You could call the mysql_num_rows function on a result set containing all the rows to find out.

$result = mysql_query('SELECT * FROM TABLE GROUP BY Table.Table_ID');
$row_count = mysql_num_rows($result);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜