在PostgreSQL中显示表(来自MySQL)的等价物是什么?


当前回答

\dt将列出表,\pset pager off将在同一窗口中显示它们,而不切换到单独的窗口。喜欢dbshell中的那个功能。

其他回答


使用psql:\dt

Or:

SELECT c.relname AS Tables_in FROM pg_catalog.pg_class c
        LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE pg_catalog.pg_table_is_visible(c.oid)
        AND c.relkind = 'r'
        AND relname NOT LIKE 'pg_%'
ORDER BY 1

该SQL查询适用于大多数PostgreSQL版本,非常简单。

select table_name from information_schema.tables where table_schema='public' ;

请注意,仅\dt将列出您正在使用的数据库的公共模式中的表。我喜欢将表保存在单独的模式中,因此接受的答案对我来说不起作用。

要列出特定模式中的所有表,我需要:

1) 连接到所需的数据库:

psql mydb

2) 指定要在\dt命令后查看表的架构名称,如下所示:

\dt myschema.*

这显示了我感兴趣的结果:

               List of relations
 Schema   |       Name      | Type  |  Owner   
----------+-----------------+-------+----------
 myschema | users           | table | postgres
 myschema | activity        | table | postgres
 myschema | roles           | table | postgres

作为一个快速的oneliner

# just list all the postgres tables sorted in the terminal
db='my_db_name'
clear;psql -d $db -t -c '\dt'|cut -c 11-|perl -ne 's/^([a-z_0-9]*)( )(.*)/$1/; print'

或者如果您更喜欢更清晰的json输出多行:

IFS='' read -r -d '' sql_code <<"EOF_CODE"
    select array_to_json(array_agg(row_to_json(t))) from (
        SELECT table_catalog,table_schema,table_name 
        FROM information_schema.tables
        ORDER BY table_schema,table_name ) t
EOF_CODE
psql -d postgres -t -q -c "$sql_code"|jq

以超级用户身份登录:

sudo -u postgres psql

您可以通过\l命令列出所有数据库和用户,(通过\?列出其他命令)。

现在,如果您想查看其他数据库,可以通过\c命令(如\c template1、\c postgres postgress)更改用户/数据库,并使用\d、\dt或\dS查看表/视图等。