sqlite 查询以获取 table 名称的所有列表以及其中的记录数

sqlite query to get all list of table names with number of records in it

请帮助解决以下问题: sqlite 查询以获取所有 table 名称的列表,其中包含记录数:

我想获取 Sqlite3 数据库中每个 table 的行数。我想避免写出手写查询。我可以这样得到 table 的列表:

SELECT 名称来自 sqlite_master WHERE 类型='table' 我想在这样的子查询中使用它:

select count (*) from (SELECT name FROM sqlite_master WHERE type='table'); 但只会 return 子查询中的总行数,这不是我想要的。

也许你使用了ANALYZE to create a workaround. It creates the internal schema object sqlite_stat1

的结果

2.6.3. The sqlite_stat1 table

The sqlite_stat1 is an internal table created by the ANALYZE command and used to hold supplemental information about tables and indexes that the query planner can use to help it find better ways of performing queries. Applications can update, delete from, insert into or drop the sqlite_stat1 table, but may not create or alter the sqlite_stat1 table. The schema of the sqlite_stat1 table is as follows:

CREATE TABLE sqlite_stat1(tbl,idx,stat);

There is normally one row per index, with the index identified by the name in the sqlite_stat1.idx column. The sqlite_stat1.tbl column is the name of the table to which the index belongs. In each such row, the sqlite_stat.stat column will be a string consisting of a list of integers followed by zero or more arguments. The first integer in this list is the approximate number of rows in the index. (The number of rows in the index is the same as the number of rows in the table, except for partial indexes.) .....

如果没有部分索引,SELECT tbl,cast(stat as INT) 将 return 每个 table 中的行数,除非 table 有 0 行。

此 sql 给出了小型(25MB、34 tables、26 个索引、33K+ 行)生产数据库的预期结果。您的里程可能(将?)有所不同。

ANALYZE;
select  DISTINCT tbl_name, CASE WHEN stat is null then 0 else cast(stat as INT) END numrows 
from sqlite_master m 
LEFT JOIN sqlite_stat1 stat on   m.tbl_name = stat.tbl 
where m.type='table'
and m.tbl_name not like 'sqlite_%'
order by 1;
--drop table sqlite_stat1;