简体   繁体   中英

How to get total number of rows in a MySQL database?

I have many tables in my MYSQL database. I want to be able to echo the total number of all the rows in a database.

So basically I want to have it so the circled sum in the image below is echoed in PHP. 在此处输入图片说明

This is my current code for just displaying the total rows from one table ($txid). I have tried replaced $txid with * but it doesnt work. Any help is greatly appreciated. Thanks.

mysql_select_db($dbname);

$result = mysql_query("select count(1) FROM $txid");
$row = mysql_fetch_array($result);

$total = $row[0];
echo $total;

?>

Use the schema:

SELECT SUM(TABLE_ROWS) 
FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_SCHEMA = '{DB_NAME}'

That is what phpmyadmin is using.

Source: Get record counts for all tables in MySQL database

There is no way to "wildcard" across multiple tables - this is one reason why normalized [row-oriented] designs are good .

Instead, the query (or queries) must be written in such a way that that all the tables are specified manually - that is, there is a separate SELECT per table. These can then be grouped with UNION ALL and SUM'ed, or summed in PHP after running each query individually.

select SUM(i) as total
from (
  select count(*) as i FROM tx
  union all
  select count(*) as i FROM tx2
  -- repeated for each table
) counts

(The SQL can be generated dynamically in PHP or in MySQL from a list of the tables to query.)

If you only need a rough estimate , then the INFORMATION_SCHEMA TABLES.TABLE_ROWS table can be queried - and indeed this presents a row-oriented design . However, at least for InnoDB tables, this is not guaranteed to return the same results as a direct COUNT.

For InnoDB tables, the row count is only a rough estimate used in SQL optimization.

Use the INFORMATION_SCHEMA database. It's always a nice way to obtain meta data information:

SELECT SUM(TABLE_ROWS)
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_SCHEMA = 'your_database';

And here's your updated PHP code:

mysql_select_db($dbname);

$result = mysql_query("SELECT SUM(TABLE_ROWS) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '$dbname'");
$row = mysql_fetch_array($result);

$total = $row[0];
echo $total;

Read more about INFORMATION_SCHEMA.TABLES

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM