我已经在postgreSQL中创建了一个表。我想查看用于创建表的SQL语句,但无法找出它。

如何通过命令行或SQL语句获得Postgres中现有表的创建表SQL语句?


当前回答

在pgadminIII数据库>>schema >>tables>>右键单击“Your table”>>scripts>>“选择任何一个(创建,插入,更新,删除..)”

其他回答

你也可以使用一个免费的数据库管理工具,比如DBeaver,它允许你查看表的DDL,这里有一个例子:

如果你想找到一个表的create语句而不使用pg_dump,这个查询可能对你有用(改变'tablename'与你的表被称为什么):

SELECT                                          
  'CREATE TABLE ' || relname || E'\n(\n' ||
  array_to_string(
    array_agg(
      '    ' || column_name || ' ' ||  type || ' '|| not_null
    )
    , E',\n'
  ) || E'\n);\n'
from
(
  SELECT 
    c.relname, a.attname AS column_name,
    pg_catalog.format_type(a.atttypid, a.atttypmod) as type,
    case 
      when a.attnotnull
    then 'NOT NULL' 
    else 'NULL' 
    END as not_null 
  FROM pg_class c,
   pg_attribute a,
   pg_type t
   WHERE c.relname = 'tablename'
   AND a.attnum > 0
   AND a.attrelid = c.oid
   AND a.atttypid = t.oid
 ORDER BY a.attnum
) as tabledefinition
group by relname;

当直接从psql调用时,这样做是有用的:

\pset linestyle old-ascii

另外,这个线程中的generate_create_table_statement函数工作得很好。

如果您不想创建函数,而只想让查询创建一个基本的表结构,这里有一个解决方案。

select 'CREATE TABLE ' || table_name ||'(' ||STRING_AGG (
    column_name || ' ' || data_type ,
        ','
       ORDER BY
        table_name,
        ordinal_position
    ) ||');'
    from 
information_schema.columns 
where table_schema = 'public'
group by 
table_name

这是对我有用的变化:

pg_dump -U user_viktor -h localhost unit_test_database -t floorplanpreferences_table——schema-only

此外,如果你正在使用模式,你当然也需要指定:

pg_dump -U user_viktor -h localhost unit_test_database -t "949766e0-e81e-11e3-b325-1cc1de32fcb6"。floorplanpreferences_table——模式

您将得到一个输出,可以用来再次创建表,只需在psql中运行该输出。

DataGrip具有与pgAdmin相同的功能。你可以右键点击一个表,你会看到选项自动生成创建表语句。