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

标签 sqlite system.data.sqlite

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

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

SELECT name FROM sqlite_master WHERE type='table' 我想在这样的子查询中使用它:

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

最佳答案

也许您使用 ANALYZE 的结果创建解决方法。它创建内部模式对象 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) 将返回每个表中的行数,除非该表有 0 行。

此 sql 在小型(25MB、34 个表、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;

关于sqlite查询以获取所有表名列表及其中的记录数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56323786/

相关文章:

sql - 有没有更有效的方法来编写这个 SQL 查询来删除不同的值?

java - 从 JAVA 中的游标获取 SQL 命令(android)

java - Android自动SQL插入

sqlite - 是否可以将sqlite中的 '0'字符保存为文本

iphone - sqlite 查询导致 iPhone 应用程序崩溃 - 内存问题

sql - sqlite3中的case表达式

xamarin - System.Data.SQLite 和 sqlite-net-pcl 的区别

c# - ON CONFLICT 甚至没有用错误语法编译?

C# Failed to find or load the registered .Net Data Provider错误

c# - System.Data.SQLite parseViaFramework