您可以简单地查询元数据:
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;
SQL Fiddle 示例
这实质上会生成与解决方案相同的 SQL UNION ALL
,但会根据主表的内容创建 SQL。