计算每个表的行数(从子查询返回表名)

时间:2013-04-04 07:14:59

标签: mysql sql database

我正在从表格中进行查询,该表格给出了表格列表(基于不同的条件列表会有所不同) 我想显示表名列表及其行数。我怎样才能做到这一点?

我试过了

select count(*) from (select tablename from main_table) as t;

但它只返回main_table中的条目数,但不返回每个表中条目的数量 我可以使用系统表来获取rowcount,但我不想要所有表但只需要特定的表,并且可能需要特定查询的行数。

Algo就是这样的

for tablenames in main_table where id>3:
    select count(*) from tablename where constraints    

4 个答案:

答案 0 :(得分:4)

尝试这样的事情:

SELECT table_name, table_type, SUM(TABLE_ROWS) 
FROM information_schema.tables
WHERE table_schema = 'db5' -- or your own schema
    AND  table_type ='BASE TABLE'
    AND table_name LIKE 'mytables%'
GROUP BY table_name, table_type

或者这个

SELECT table_name, TABLE_ROWS FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_SCHEMA = '{your_db}'; 

答案 1 :(得分:3)

您可以简单地查询元数据:

SELECT  Table_Name, table_rows
FROM    INFORMATION_SCHEMA.TABLES
WHERE   TABLE_TYPE = 'BASE TABLE'
AND     TABLE_SCHEMA = 'YourDatabase';

或者您需要使用UNION ALL

SELECT  'T1' AS TableName, COUNT(*) AS Rows
FROM    T1
UNION ALL
SELECT  'T2' AS TableName, COUNT(*) AS Rows
FROM    T2
UNION ALL
SELECT  'T3' AS TableName, COUNT(*) AS Rows
FROM    T3;

如果需要动态完成,那么可以使用动态SQL:

SET @SQL = (SELECT GROUP_CONCAT('SELECT ''', 
                                TableName, 
                                ''' AS TableName, COUNT(*) AS Rows FROM ', 
                                TableName SEPARATOR ' UNION ALL ')
            FROM MainTable
            --WHERE Some condition to limit tables
            );

PREPARE stmt FROM @SQL;
EXECUTE stmt;

<强> Example on SQL Fiddle

这实际上产生与UNION ALL解决方案相同的SQL,但是根据主表的内容创建SQL。

答案 2 :(得分:0)

以下是动态SQL的示例,如果要创建包含三列的表:
1st是Table Name并且包含main_table的表名,2nd是Column X,在main_table的列User Name中包含单引号(')char,第三个是Rows包含Table Name中每个表的行数:

    SET @SQL = (select GROUP_CONCAT('SELECT ''', 
                                    `Table Name `,
                                    ''' AS `Table Name`,
                                    ', quote(`User Name`), ',
                                    COUNT(*) AS Rows FROM `',
                                    `Table Name` SEPARATOR '` UNION ALL ')
                                    FROM `.tables`
               );
    PREPARE stmt FROM @SQL;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;

答案 3 :(得分:-1)

如果选择动态SQL,并且某些列名称包含空格,则会发生错误。在这种情况下,只能通过INFORMATION_SCHEMA.TABLES工作元数据(如果您有权使用它),而不是动态SQL查询!
假定您有表,该表的列名Table Name包含现有其他表的名称(带空格)。
如果要使用动态SQL,并且某些列名称包含空格,则正确的查询为:

    SET @SQL = (select GROUP_CONCAT('SELECT ''', 
                                `Table Name`,
                                ''' AS `Table Name`,
                                COUNT(*) AS Rows FROM `',
                                `Table Name` SEPARATOR '` UNION ALL ')
            FROM main_table
            );
    PREPARE stmt FROM @SQL;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;