如何在 PostgreSQL 中仅获取数据库的 table 名称

How to get only the table names of a database in PostgreSQL

我有几个 bash 脚本可以查询 mysql 数据库并获取 table 名称,我使用以下命令:

mysql -NBA --user=$DB_user --password=$DB_pass --database=$DB_name -e 'show tables'

使用 -NBA 参数过滤结果并得到如下内容:

    categories
    colections
    colors
    files

在带有 psql 的 postgreSQL 中,我正在尝试实现相同的格式,我正在阅读文档并使用以下参数:

psql --username=$DB_user -W --host=$HOST --dbname=$DB_name -Atc '\dt'

这是我能得到的最好的

    public|categories|table|user
    public|colections|table|dbuser
    public|colors|table|dbuser
    public|files|table|dbuser

在最坏的情况下,我需要解析它以仅获取 table 的名称,但如果有人知道实现我想要的方法,我会很高兴。

此 SQL 查询获取所需信息(或其任何变体):

SELECT table_name
FROM   information_schema.tables
WHERE  table_schema = 'public' -- mysql does not have schemas
ORDER  BY 1;

所以从 shell:

psql --username=$DB_user -W --host=$HOST --dbname=$DB_name -Atc 'SELECT table_name FROM information_schema.tables WHERE table_schema = \'public\' ORDER BY 1'

您可能想使用 quote_ident(table_name) 来转义 table 名称:

;DELETE FROM users; -- 变为 ";DELETE FROM users; --"

  • Function to loop through and select data from multiple tables
  • Table name as a PostgreSQL function parameter

请注意,您只能获得当前用户有权访问的 table 个名称。关于信息架构和系统目录:

  • How to check if a table exists in a given schema