Count table rows

后端 未结 11 1782
一个人的身影
一个人的身影 2020-11-28 21:55

What is the MySQL command to retrieve the count of records in a table?

相关标签:
11条回答
  • 2020-11-28 22:35

    Because nobody mentioned it:

    show table status;
    

    lists all tables along with some additional information, including estimated rows for each table. This is what phpMyAdmin is using for its database page.

    This information is available in MySQL 4, probably in MySQL 3.23 too - long time prior information schema database.

    UPDATE:

    Because there was down-vote, I want to clarify that the number shown is estimated for InnoDB and TokuDB and it is absolutely correct for MyISAM and Aria (Maria) storage engines.

    Per the documentation:

    The number of rows. Some storage engines, such as MyISAM, store the exact count. For other storage engines, such as InnoDB, this value is an approximation, and may vary from the actual value by as much as 40% to 50%. In such cases, use SELECT COUNT(*) to obtain an accurate count.

    This also is fastest way to see the row count on MySQL, because query like:

    select count(*) from table;
    

    Doing full table scan what could be very expensive operation that might take hours on large high load server. It also increase disk I/O.

    The same operation might block the table for inserts and updates - this happen only on exotic storage engines.

    InnoDB and TokuDB are OK with table lock, but need full table scan.

    0 讨论(0)
  • 2020-11-28 22:41

    Simply:

    SELECT COUNT(*) FROM `tablename`
    
    0 讨论(0)
  • 2020-11-28 22:45

    If you have a primary key or a unique key/index, the faster method possible (Tested with 4 millions row tables)

    SHOW INDEXES FROM "database.tablename" WHERE Key_Name=\"PRIMARY\"
    

    and then get cardinality field (it is close to instant)

    Times where from 0.4s to 0.0001ms

    0 讨论(0)
  • 2020-11-28 22:46
    select count(*) from YourTable
    
    0 讨论(0)
  • 2020-11-28 22:48
    SELECT COUNT(*) FROM fooTable;
    

    will count the number of rows in the table.

    See the reference manual.

    0 讨论(0)
  • 2020-11-28 22:48
    $sql="SELECT count(*) as toplam FROM wp_postmeta WHERE meta_key='ICERIK' AND post_id=".$id;
    $total = 0;
    $sqls = mysql_query($sql,$conn);
    if ( $sqls ) {
        $total = mysql_result($sqls, 0);
    };
    echo "Total:".$total;`
    
    0 讨论(0)
提交回复
热议问题