Jon*_*nas 106 postgresql database-design
如果我有一个包含列的表:
id | name | created_date
Run Code Online (Sandbox Code Playgroud)
并想添加一列,我使用:
alter table my_table add column email varchar(255)
Run Code Online (Sandbox Code Playgroud)
然后在列之后添加created_date列。
有什么办法可以指定新列的位置吗?例如,我可以在之后添加它name并得到一个表格,如:
id | name | email | created_date
Run Code Online (Sandbox Code Playgroud)
Mar*_*ian 75
ALTER TABLE ADD COLUMN只会在最后添加新列,作为最后一列。为了在另一个位置创建一个新列,您需要重新创建表并将旧表/当前表中的数据复制到这个新表中。
Sco*_*owe 26
如果您想要某个顺序,则需要重新创建表。只需执行以下操作:
alter table tablename rename to oldtable;
create table tablename (column defs go here);
insert into tablename (col1, col2, col3) select col2, col1, col3 from oldtable;
Run Code Online (Sandbox Code Playgroud)
根据需要创建索引等。
小智 6
如果你只是为了外观而想要这个,我发现为每个表保留一个具有所需列顺序的视图,并从中选择而不是表更容易。
create table my_table (
create view view_my_table as
select id, name, created_date from my_table;
-- adding a new column
begin;
alter table my_table add column email varchar(255);
drop view view_my_table;
create view view_my_table as
select id, name, email, created_date from my_table;
commit;
Run Code Online (Sandbox Code Playgroud)
对于所有其他目的(如插入、联合),最好始终指定列列表。
-- bad
insert into my_table values (...);
(select * from my_table)
union all
(select * from my_table);
-- good
insert into my_table (id, name, email, created_date) values (...);
(select id, name, email, created_date from my_table)
union all
(select id, name, email, created_date from my_table);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
124924 次 |
| 最近记录: |