AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / dba / Perguntas / 75451
Accepted
sjdh
sjdh
Asked: 2014-09-02 16:11:01 +0800 CST2014-09-02 16:11:01 +0800 CST 2014-09-02 16:11:01 +0800 CST

mostre o nome da tabela + número de registros para cada tabela em um banco de dados mysql innodb

  • 772

Como listar todas as tabelas do banco de dados atual, junto com o número de linhas da tabela.

Em outras palavras, você pode pensar em uma consulta para chegar a algo assim no mysql?

+------------------------++------------------------+
| Tables_in_database     |  Number of rows         |
+------------------------++------------------------+
| database 1             |   1000                  |
| database 2             |   1500                  |
+------------------------++------------------------+

Diferentes abordagens são bem-vindas.

mysql innodb
  • 4 4 respostas
  • 16017 Views

4 respostas

  • Voted
  1. Best Answer
    RolandoMySQLDBA
    2014-09-02T18:59:08+08:002014-09-02T18:59:08+08:00

    Eu tenho uma abordagem muito agressiva usando força bruta Dynamic SQL

    SET group_concat_max_len = 1024 * 1024 * 100;
    SELECT CONCAT('SELECT * FROM (',GROUP_CONCAT(CONCAT('SELECT ',QUOTE(tb),' Tables_in_database,
    COUNT(1) "Number of Rows" FROM ',db,'.',tb) SEPARATOR ' UNION '),') A;')
    INTO @sql FROM (SELECT table_schema db,table_name tb
    FROM information_schema.tables WHERE table_schema = DATABASE()) A;
    PREPARE s FROM @sql; EXECUTE s; DEALLOCATE PREPARE s;
    

    Exemplo: No meu banco de dados de teste, recebo isso

    mysql> use test
    Database changed
    mysql> SET group_concat_max_len = 1024 * 1024 * 100;
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> SELECT CONCAT('SELECT * FROM (',GROUP_CONCAT(CONCAT('SELECT ',QUOTE(tb),' Tables_in_database,
        '> COUNT(1) "Number of Rows" FROM ',db,'.',tb) SEPARATOR ' UNION '),') A;')
        -> INTO @sql FROM (SELECT table_schema db,table_name tb
        -> FROM information_schema.tables WHERE table_schema = DATABASE()) A;
    Query OK, 1 row affected (0.00 sec)
    
    mysql> PREPARE s FROM @sql; EXECUTE s; DEALLOCATE PREPARE s;
    Query OK, 0 rows affected (0.00 sec)
    Statement prepared
    
    +--------------------+----------------+
    | Tables_in_database | Number of Rows |
    +--------------------+----------------+
    | biblio             |              3 |
    | biblio_old         |              7 |
    | dep                |              5 |
    | e                  |             14 |
    | emp                |              4 |
    | fruit              |             12 |
    | fruit_outoforder   |             12 |
    | nums_composite     |              0 |
    | nuoji              |              4 |
    | prod               |              3 |
    | prodcat            |              6 |
    | test2              |              9 |
    | worktable          |              5 |
    | yoshi_scores       |             24 |
    +--------------------+----------------+
    14 rows in set (0.00 sec)
    
    Query OK, 0 rows affected (0.00 sec)
    
    mysql>
    

    DE UMA CHANCE !!!

    CAVEAT : Se todas as tabelas forem MyISAM, isso acontecerá muito rápido. Se todas as tabelas forem InnoDB, cada tabela será contada. Isso pode ser brutal e implacável para tabelas InnoDB muito grandes.

    • 9
  2. Pydi Raju
    2014-09-02T23:26:42+08:002014-09-02T23:26:42+08:00

    Tente a consulta abaixo sem consulta dinâmica

    SELECT Table_name AS TablesInDatabase ,table_rows AS NumberOfRows 
    FROM information_schema.tables 
    WHERE Table_schema=DATABASE(); 
    
    • 6
  3. RikW
    2018-03-22T00:03:33+08:002018-03-22T00:03:33+08:00

    Talvez esta consulta possa ajudar. Ele mostra o tamanho dos dados e o número de registros.

    SET @table=(SELECT DATABASE());
    select @table;
    SELECT 
         table_schema as `Database`, 
         table_name AS `Table`, 
         round(((data_length + index_length) / 1024 / 1024), 2) `Size in MB`,
         table_rows as 'Rows'
    FROM information_schema.TABLES 
    WHERE table_schema = @table
    ORDER BY (data_length + index_length) DESC;
    
    • 1
  4. Sarita
    2018-12-07T02:33:24+08:002018-12-07T02:33:24+08:00

    Obtenha contagens exatas de linhas para todas as tabelas no MySQL usando shell script.

    defina o parâmetro no arquivo parameter.config como

    # Server Details
    host_server=10.109.25.37
    
    # Mysql credentials
    mysql_user=root
    mysql_pass=root
    mysql_port=3306
    

    O script para contar é:

    #!/bin/bash
    # This Script is used to take rows count of mysql all user database
    
    # Read Parameter
    source parameter.config
    
    # Find path
    MY_PATH="`dirname \"$0\"`"
    #echo "$MY_PATH"
    
    start=`date +%s`
    echo -e "\n\n"
    echo MySQL script start runing at Date and Time is: `date +"%D %T"`
    echo -e "@@@ Start of rows Count of MySQL on Old Ficus Release $host_server @@@"
    
    echo -e "\n***** MySQL Rows Count Start *****"
    
    #Make directory to save rows count
    NOW="$(date +%Y%m%dT%H%M%S)"
    dir_name="mysqlRows_$host_server"
    if [ ! -d "$MY_PATH/$dir_name" ]; then
        mkdir "$MY_PATH/$dir_name"
    fi
    echo -e "\n..... Directory $dir_name is Created for mysql....."
    
    echo -e "\n..... Check MySQL Connection ....."
    # Verifying mysql connections on new release machine
    MYSQL_CONN="-u$mysql_user -p$mysql_pass -h$host_server"
    mysql ${MYSQL_CONN} -e "exit"
    if [ $? -eq 0 ];
    then
        echo -e "\n..... MySQL Database Connection Successful on server $host_server ....."
    else
        echo -e "\n..... MySQL Database Connection Fail. Please verify $host_server credential ....."
        exit
    fi
    
    echo -e "\nReading MySQL database names..."
    mysql ${MYSQL_CONN} -ANe "SELECT schema_name FROM information_schema.schemata WHERE schema_name NOT IN ('mysql','information_schema','performance_schema')" > $MY_PATH/$dir_name/dbs_$NOW.txt
    DBS="$(cat $MY_PATH/$dir_name/dbs_$NOW.txt)"
    # echo -e "\nList of databases:\t" ${DBS}
    
    echo -e "\n..... Running for row count of tables of all user databases ....."
    
    # All User databases
    for db in ${DBS[@]}
    do
        # echo $db , ${db[@]} 
        # Find list of database
        echo -e "\n\t... Running for ${db[@]} database tables list ..."
        mysql ${MYSQL_CONN} -ANe "SELECT  TABLE_NAME FROM information_schema.TABLES WHERE  TABLE_SCHEMA IN ('${db[@]}')" > $MY_PATH/$dir_name/${db[@]}_tables_$NOW.txt
        TBL="$(cat $MY_PATH/$dir_name/${db[@]}_tables_$NOW.txt)"
        # echo "Table in $db are:" ${TBL[@]}, $MY_PATH/$dir_name/${db[@]}_tables.txt
    
        echo -e "\n\t... Running for ${db[@]} database tables rows count ..."
        for tbs in ${TBL[@]}
        do
            # echo $tbs , ${tbs[@]}
            count=$(mysql -u$mysql_user -p$mysql_pass -h$host_server ${db[@]} -N -e "select count(*) from ${tbs[@]}")
            # count="$(cat /tmp/$db_rows_$NOW.txt)"
            # echo "Row in $tb Table of $db database are:" ${count[@]}
            echo -e "${db[@]},${tbs[@]},$count" >> $MY_PATH/$dir_name/${db[@]}_rows_$NOW.csv
            echo -e "${db[@]},${tbs[@]},$count" >> $MY_PATH/$dir_name/alldbs_rows_$NOW.csv
        done
    done
    echo -e "\n..... End of rows count of tables of all databases ....."
    
    echo -e "\n===== MySQL Rows Count End ====="
    
    # Display script execution time.
    echo -e "@@@ Completion of Rows Count of MySQL on old Release $host_server @@@"
    echo Script ended at Date and Time is: `date +"%D %T"`
    end=`date +%s`
    runtime=$((end-start))
    echo -e "Time(in second) taken for running MySQL row count script:" $runtime "Sec."
    

    salve isso no arquivo "mysqlrowscount.sh", execute este script usando o comando:

    bash mysqlrowscount.sh
    
    • 1

relate perguntas

  • Existem ferramentas de benchmarking do MySQL? [fechado]

  • Onde posso encontrar o log lento do mysql?

  • Como posso otimizar um mysqldump de um banco de dados grande?

  • Quando é o momento certo para usar o MariaDB em vez do MySQL e por quê?

  • Como um grupo pode rastrear alterações no esquema do banco de dados?

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host

    • 12 respostas
  • Marko Smith

    Como fazer a saída do sqlplus aparecer em uma linha?

    • 3 respostas
  • Marko Smith

    Selecione qual tem data máxima ou data mais recente

    • 3 respostas
  • Marko Smith

    Como faço para listar todos os esquemas no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Listar todas as colunas de uma tabela especificada

    • 5 respostas
  • Marko Smith

    Como usar o sqlplus para se conectar a um banco de dados Oracle localizado em outro host sem modificar meu próprio tnsnames.ora

    • 4 respostas
  • Marko Smith

    Como você mysqldump tabela (s) específica (s)?

    • 4 respostas
  • Marko Smith

    Listar os privilégios do banco de dados usando o psql

    • 10 respostas
  • Marko Smith

    Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Como faço para listar todos os bancos de dados e tabelas usando o psql?

    • 7 respostas
  • Martin Hope
    Jin conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host 2014-12-02 02:54:58 +0800 CST
  • Martin Hope
    Stéphane Como faço para listar todos os esquemas no PostgreSQL? 2013-04-16 11:19:16 +0800 CST
  • Martin Hope
    Mike Walsh Por que o log de transações continua crescendo ou fica sem espaço? 2012-12-05 18:11:22 +0800 CST
  • Martin Hope
    Stephane Rolland Listar todas as colunas de uma tabela especificada 2012-08-14 04:44:44 +0800 CST
  • Martin Hope
    haxney O MySQL pode realizar consultas razoavelmente em bilhões de linhas? 2012-07-03 11:36:13 +0800 CST
  • Martin Hope
    qazwsx Como posso monitorar o andamento de uma importação de um arquivo .sql grande? 2012-05-03 08:54:41 +0800 CST
  • Martin Hope
    markdorison Como você mysqldump tabela (s) específica (s)? 2011-12-17 12:39:37 +0800 CST
  • Martin Hope
    Jonas Como posso cronometrar consultas SQL usando psql? 2011-06-04 02:22:54 +0800 CST
  • Martin Hope
    Jonas Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL? 2011-05-28 00:33:05 +0800 CST
  • Martin Hope
    Jonas Como faço para listar todos os bancos de dados e tabelas usando o psql? 2011-02-18 00:45:49 +0800 CST

Hot tag

sql-server mysql postgresql sql-server-2014 sql-server-2016 oracle sql-server-2008 database-design query-performance sql-server-2017

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve