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

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

问题描述

如何使用postgres在表的第二列或第三列之后添加表中的新列?



我的代码如下

 更改表n_domains在owner_id 


<之后添加列contract_nr int div class = h2_lin>解决方案

不,没有直接的方法可以做到这一点。这是有原因的-每个查询都应按其需要的顺序(以及格式等)列出所需的所有字段,从而使一个表中列的顺序无关紧要。



如果确实需要这样做,我可以考虑一种解决方法:




  • 转储并将表的描述保存在问题(使用 pg_dump --schema-only --table =< schema.table> ...

  • 添加列您想在保存的定义中找到它的位置

  • 重命名保存的定义中的表,以免在尝试创建旧表时与旧表的名称发生冲突

  • 使用此定义创建新表

  • 使用 INSERT INTO < new_table> 选择字段1,字段2,< default_for_new_field> ,字段3,... FROM < old_table> ';

  • 重命名旧表

  • 重命名新表将表恢复为原始名称

  • 在确保一切正常之后,最终将旧的重命名表删除


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在表格的第二列或第三列之后添加表格中的新列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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