MYSQL的FOUND_ROWS()函數

For a SELECT with a LIMIT clause, the number of rows that would be returned were there no LIMIT clause

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

 

比如說有段sql需要取出一張表的前10行,同時又需要取出符合條件的總數。這在某些翻頁操作中很常見:   SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name WHERE id > 100 LIMIT 10;

在上一查詢之後,你只需要用FOUND_ROWS()就能獲得查詢總數,這個數目是拋掉了LIMIT之後的結果數:SELECT FOUND_ROWS();

其中第一個sql裏面的SQL_CALC_FOUND_ROWS不可省略,它表示需要取得結果數,也是後面使用FOUND_ROWS()函數的鋪墊。

 

  1. $query = "SELECT SQL_CALC_FOUND_ROWS * FROM title WHERE ID >1000 LIMIT 10;"
  2. $result = $db->query($query); 
  3. $line = $db->fetch_row($db->query("SELECT FOUND_ROWS();")); 
  4. print_r($line); 

此時,不用額外的查詢,即可得到

 

  1. SELECT count(id) FROM tabled WHERE id>1000; 

這樣子的結果了。

不過,http://dev.mysql.com/doc/refman/5.1/zh/optimization.html#limit-optimization 說:
只要MySQL已經發送了需要的行數到客戶,它將放棄查詢,除非你正使用SQL_CALC_FOUND_ROWS

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章