检查sqlalchemy表是否为空 [英] Check whether sqlalchemy table is empty
问题描述
我需要知道是否任何给定的sqlalchemy表(sqlalchemy.schema.Table)都具有0行。我有很多表,每个表中都有很多行,并且这些表必须在启动时为所有表运行,因此我正在从运行时的角度寻找最有效的方法。因此,仅计算一项不是我想要的。如果数据库有任何更改,则该数据库为PostgreSQL
I need to know whether any given sqlalchemy table (sqlalchemy.schema.Table) has exactly 0 rows. I have a lot of tables with a lot of rows in each and this has to run for all of them at startup so I am looking for the most efficient way to do this from a runtime perspective. So, just doing a count is not what I am looking for. The database is PostgreSQL if that changes anything
推荐答案
SQLAlchemy将允许您执行原始查询。在PostgreSQL中,您可以查询元数据中的n_live_tup以获取记录数:
SQLAlchemy will allow you to do a "raw" query. In PostgreSQL, you can query the meta data for n_live_tup to get the record count:
SELECT
schemaname as schema_name,
relname as table_name,
n_live_tup as record_count
FROM pg_stat_user_tables WHERE n_live_tup > 0;
很显然,这为您提供了具有实时记录的所有表格。如果只希望没有,则将其更改为 WHERE n_live_tup = 0
,如果要将其限制为仅某个表,请添加 table_name =< ;< your_table_name>>>
到where子句。
obviously, this gives you all of the tables with live records. If you only want the ones without, change the to WHERE n_live_tup = 0
and if you want to limit it to only a certain table add table_name = <<your_table_name>>
to the where clause.
如果您没有具有权限的角色,而您只想看看表是否为空,那么您可以始终执行以下操作:
If you don't have a role with permissions, and you just want to see if the table is empty, then you can alway do this:
SELECT True FROM <<your_table_name>> LIMIT 1;
如果表中有记录,则返回True,否则返回NULL。
This will return True if the table has records or NULL if it doesn't.
这篇关于检查sqlalchemy表是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!