Hướng dẫn select num rows mysql

When you COUNT(*) it takes in count column indexes, so it will be the best result. MySQL with MyISAM engine actually stores row count, it doesn't count all rows each time you try to count all rows. (based on primary key's column)

Using PHP to count rows is not very smart, because you have to send data from MySQL to PHP. Why do it when you can achieve the same on the MySQL side?

If the COUNT(*) is slow, you should run EXPLAIN on the query, and check if indexes are really used, and where they should be added.


The following is not the fastest way, but there is a case, where COUNT(*) doesn't really fit - when you start grouping results, you can run into a problem where COUNT doesn't really count all rows.

The solution is SQL_CALC_FOUND_ROWS. This is usually used when you are selecting rows but still need to know the total row count (for example, for paging). When you select data rows, just append the SQL_CALC_FOUND_ROWS keyword after SELECT:

SELECT SQL_CALC_FOUND_ROWS [needed fields or *] FROM table LIMIT 20 OFFSET 0;

After you have selected needed rows, you can get the count with this single query:

SELECT FOUND_ROWS();

FOUND_ROWS() has to be called immediately after the data selecting query.


In conclusion, everything actually comes down to how many entries you have and what is in the WHERE statement. You should really pay attention on how indexes are being used, when there are lots of rows (tens of thousands, millions, and up).

Bài viết này sẽ hướng dẫn nhiều cách khác nhau để lấy số lượng bản ghi trong database.

Đếm số bản ghi trong 1 bảng

Trong MySQL để đếm số bản ghi trong 1 bảng ta dùng lệnh:

SELECT 
    COUNT(*)
FROM
    table_name;

Ví dụ, lấy số bản ghi của bảng customers trong sample database:

SELECT 
    COUNT(*)
FROM
    customers;

+----------+
| COUNT(*) |
+----------+
|      122 |
+----------+
1 row in set (0.01 sec)

Đếm số bản ghi của 2 hay nhiều bảng

Trong MySQL để đếm số bản ghi của nhiều bảng, bạn sử dụng toán tử UNION để tập hợp các kết quả trả về trong mỗi câu lệnh SELECT.

Ví dụ, đếm số bản ghi của bảng customersorders:

SELECT 
    'customers' tablename, 
     COUNT(*) rows
FROM
    customers 
UNION 
SELECT 
    'orders' tablename, 
     COUNT(*) rows
FROM
    orders;

+-----------+------+
| tablename | rows |
+-----------+------+
| customers |  122 |
| orders    |  326 |
+-----------+------+
2 rows in set (0.01 sec)

Đếm số bản ghi của tất cả bảng trong database

Các bước sau sẽ giúp bạn đếm số bản ghi của tất cả bảng trong database classicmodels

  1. Bước 1: Lấy tên tất cả tên bảng
  2. Bước 2: Tạo lệnh SQL bao gồm tất cả lệnh SELECT COUNT(*) FROM table_name từ tất cả các bảng đã được phân tách bởi UNION
  3. Bước 3: Thực thi lệnh

Bước 1: lấy tất cả tên bảng, bạn truy vấn từ database information_schema:

SELECT 
    table_name
FROM
    information_schema.tables
WHERE
    table_schema = 'classicmodels'
        AND table_type = 'BASE TABLE';

+--------------+
| TABLE_NAME   |
+--------------+
| customers    |
| employees    |
| offices      |
| orderdetails |
| orders       |
| payments     |
| productlines |
| products     |
+--------------+
8 rows in set (0.02 sec)

Bước 2: Tạo lệnh SQL, ở đây sử dụng hàm GROUP_CONCATCONCAT:

SELECT 
    CONCAT(GROUP_CONCAT(CONCAT('SELECT \'',
                        table_name,
                        '\' table_name,COUNT(*) rows FROM ',
                        table_name)
                SEPARATOR ' UNION '),
            ' ORDER BY table_name')
INTO @sql 
FROM
    table_list;

Trong câu truy vấn này, table_list là danh sách các tên bảng là kết quả của câu truy vấn trong bước 1.

Câu truy vấn dưới sử dụng truy vấn đầu tiên như là derived table và trả về câu lệnh SQL như 1 chuỗi:

SELECT 
    CONCAT(GROUP_CONCAT(CONCAT('SELECT \'',
                        table_name,
                        '\' table_name,COUNT(*) rows FROM ',
                        table_name)
                SEPARATOR ' UNION '),
            ' ORDER BY table_name')
INTO @sql 
FROM
    (SELECT 
        table_name
    FROM
        information_schema.tables
    WHERE
        table_schema = 'classicmodels'
            AND table_type = 'BASE TABLE') table_list

Nếu MySQL của bạn từ 8.0+ thì bạn có thể dùng MySQL CTE (common table expression) thay vì derived table:

WITH table_list AS (
SELECT
    table_name
  FROM information_schema.tables 
  WHERE table_schema = 'classicmodels' AND
        table_type = 'BASE TABLE'
) 
SELECT CONCAT(
            GROUP_CONCAT(CONCAT("SELECT '",table_name,"' table_name,COUNT(*) rows FROM ",table_name) SEPARATOR " UNION "),
            ' ORDER BY table_name'
        )
INTO @sql
FROM table_list; 

Bước 3: thực thi câu lệnh @sql sử dụng các lệnh đã được chuẩn bị:

PREPARE s FROM  @sql;
EXECUTE s;
DEALLOCATE PREPARE s;

Hướng dẫn select num rows mysql

Đếm số bản ghi của tất cả bảng trong database với 1 câu truy vấn

Cách khác để lấy số bản ghi của tất cả bảng trong database là truy vấn dữ liệu trực tiếp từ database information_schema:

SELECT 
    table_name, 
    table_rows
FROM
    information_schema.tables
WHERE
    table_schema = 'classicmodels'
ORDER BY table_name;

Hướng dẫn select num rows mysql

Cách này đôi khi cho kết quả không chính xác bởi vì số bản ghi trong information_schema và số bản ghi thực tế của bảng là không được đồng bộ. Cho nên để tránh điều này thì bạn phải chạy lệnh ANALYZE TABLE trước khi đếm số bản ghi từ information_schema.

ANALYZE TABLE table_name, ...;

Hãy like, share và comment để cùng nhau học tập ! ^^