如何使用 postgres 在表中的第 2 或第 3 列之后在表中添加新列? [英] How to add a new Column in a table after the 2nd or 3rd column in the Table using postgres?

查看:68
本文介绍了如何使用 postgres 在表中的第 2 或第 3 列之后在表中添加新列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 postgres 在表格的第 2 或第 3 列之后在表格中添加新列?

我的代码如下

ALTER TABLE n_domains ADD COLUMN contract_nr int 在 owner_id 之后

解决方案

不,没有直接的方法可以做到这一点.这样做是有原因的 - 每个查询都应该以它需要的任何顺序(和格式等)列出它需要的所有字段,从而使一个表中的列的顺序变得无关紧要.

如果您真的需要这样做,我可以想到一种解决方法:

  • 转储并保存相关表的描述(使用pg_dump --schema-only --table= ...)
  • 在保存的定义中添加所需的列
  • 重命名已保存定义中的表,以免在尝试创建旧表时与旧表的名称发生冲突
  • 使用此定义创建新表
  • 使用 'INSERT INTO SELECT field1, field2, , field3,.. 用旧表中的数据填充新表. FROM

    ';
  • 重命名旧表
  • 将新表重命名为原始名称
  • 在确保一切正常后,最终删除旧的、重命名的表

How to add a new column in a table after the 2nd or 3rd column in the table using postgres?

My code looks as follows

ALTER TABLE n_domains ADD COLUMN contract_nr int after owner_id

解决方案

No, there's no direct way to do that. And there's a reason for it - every query should list all the fields it needs in whatever order (and format etc) it needs them, thus making the order of the columns in one table insignificant.

If you really need to do that I can think of one workaround:

  • dump and save the description of the table in question (using pg_dump --schema-only --table=<schema.table> ...)
  • add the column you want where you want it in the saved definition
  • rename the table in the saved definition so not to clash with the name of the old table when you attempt to create it
  • create the new table using this definition
  • populate the new table with the data from the old table using 'INSERT INTO <new_table> SELECT field1, field2, <default_for_new_field>, field3,... FROM <old_table>';
  • rename the old table
  • rename the new table to the original name
  • eventually drop the old, renamed table after you make sure everything's alright

这篇关于如何使用 postgres 在表中的第 2 或第 3 列之后在表中添加新列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆