SQL 使用单个查询重命名和更改列类型的 PostgreSQL 查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25398603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PostgreSQL query to rename and change column type with single query
提问by taufique
In PostgreSQL if I need to rename and change column data type, I should run two separate queries to do so.
在 PostgreSQL 中,如果我需要重命名和更改列数据类型,我应该运行两个单独的查询来执行此操作。
To rename:
重命名:
ALTER TABLE <tablename> RENAME <oldcolumn> TO <newcolumn>
and to change column type:
并更改列类型:
ALTER TABLE <tablename> ALTER COLUMN <columnname> <columntype>.
But is there any way to do both of these works with single query like following MySQL query:
但是有什么方法可以使用单个查询来完成这两项工作,例如以下 MySQL 查询:
ALTER TABLE <tableName> CHANGE COLUMN <oldcolumnname> <newcolumnname> <newtype>
回答by Craig Ringer
In PostgreSQL, ALTER TABLE
can take a series of operations. So:
在PostgreSQL中,ALTER TABLE
可以采取一系列的操作。所以:
ALTER TABLE <tablename> RENAME <oldcolumn> TO <newcolumn>;
ALTER TABLE <tablename> ALTER COLUMN <columnname> TYPE <newtype>;
is the same as
是相同的
ALTER TABLE <tablename>
ALTER COLUMN <columnname> TYPE <newtype>
RENAME <oldcolumn> TO <newcolumn>;
However... why? IIRC the rename won't cause a full-table scan, so there's no benefit over just doing the two statements separately, within one transaction. What problem are you actually trying to solve with this?
然而……为什么?IIRC 重命名不会导致全表扫描,因此在一个事务中单独执行两个语句没有任何好处。你实际上想用这个解决什么问题?
回答by jainvikram444
PostgreSQL: Alter table column name and data-type:
PostgreSQL:更改表列名和数据类型:
ALTER TABLE <TableName>
ALTER [ COLUMN ] column [ SET DATA ] TYPE data_type [ COLLATE collation ] [ USING expression ]
RENAME [ COLUMN ] column TO new_column;
See ALTER TABLE
.
回答by Omar
Here is the easiest way to do it.
这是最简单的方法。
ALTER TABLE your_table_name
RENAME COLUMN your_old_column_name TO your_new_column_name;