MySQL之分頁屢次查詢優化

    分頁查詢通常都會出現倆次查詢,此時會有以下狀況:html

  1. 要獲得知足條件的那一頁記錄數。
  2. 要獲得知足條件的總記錄數。

    若是在第一個查詢和第二個查詢之間新增或者刪除了一些數據,那麼查詢的結果就不許備了。我想你們都能想象這個場景,在此就不舉例。mysql

    有什麼解決方法,不會出現上述的問題,通過一番搜索,發現MySQL能夠使用sql

    List-1spa

ELECT FOUND_ROWS();

    咱們來驗證下:code

1.不帶Limit的查詢狀況

   List-2 獲得7條記錄orm

mysql> select * from student where id>5;
+----+-------+------+
| id | name  | age  |
+----+-------+------+
|  8 | ??    |   20 |
|  9 | ??    |   20 |
| 10 | ??    |   20 |
| 11 | ??    |   20 |
| 12 | ??    |   20 |
| 13 | Jack  |   16 |
| 14 | Alice |   16 |
+----+-------+------+
7 rows in set (0.00 sec)

    List-3 插入一條記錄,此時知足List-2條件的記錄是8了htm

mysql> insert into student(name,age) values('Wenlian',25);
Query OK, 1 row affected (0.01 sec)

    List-4 獲得的是7,而不是8blog

mysql> select found_rows();
+--------------+
| found_rows() |
+--------------+
|            7 |
+--------------+
1 row in set (0.01 sec)

    咱們explain來查看下"select found_rows();"文檔

    List-5 type值是null,表示不須要去查詢tableget

mysql> explain select found_rows();
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+----------------+
| id | select_type | table | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra          |
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+----------------+
|  1 | SIMPLE      | NULL  | NULL       | NULL | NULL          | NULL | NULL    | NULL | NULL |     NULL | No tables used |
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+----------------+
1 row in set, 1 warning (0.00 sec)

    

    來驗證下刪除的狀況

    List-6  知足條件的有5條

mysql> select * from student where age=16;
+----+---------+------+
| id | name    | age  |
+----+---------+------+
|  1 | ??      |   16 |
|  2 | Steven  |   16 |
|  3 | Han     |   16 |
|  4 | Meituan |   16 |
| 13 | Jack    |   16 |
+----+---------+------+
5 rows in set (0.00 sec)

    List-7 刪除一條知足List-6條件的記錄

mysql> delete from student where id=1;
Query OK, 1 row affected (0.00 sec)

    List-8 即便List-7中刪除了一條知足條件的記錄,結果仍是5

mysql> SELECT FOUND_ROWS();
+--------------+
| FOUND_ROWS() |
+--------------+
|            5 |
+--------------+
1 row in set (0.01 sec)

2.帶Limit的查詢

    這裏就再也不給出具體例子,看MySQL官網文檔,上面有具體描述。

Reference:

  1. MySQL官網: https://dev.mysql.com/doc/refman/8.0/en/information-functions.html
  2. https://blog.sqlauthority.com/2016/04/15/mysql-found_rows-function-total-number-rows-affected/
相關文章
相關標籤/搜索