在对varchar类型字段改为numeric时,无论用哪种方式都是失败,后来发现因为数据底层存储方式不同,导致这两种类型的字段都无法直接转换,删除字段重新插入字段即可。
更新字段语句(对于可相互转换的类型):
alter table “member” alter COLUMN imgfileid type int using imgfileid::int
添加字段语句:
alter table table_name add column field type
获取字段类型:
SELECT
col_description ( a.uid ) AS COMMENT,
format_type ( a.uid ) AS TYPE,
a.uid AS NAME
FROM
tb_account a
删除字段:
alter table table_name drop column column_name
更新字段名:
ALTER TABLE auth_user RENAME email TO aemail
更改表名:
alter table table_name rename to newname
添加唯一键约束
alter table tb_viewed_records add constraint uk_view_unique_from_to unique (fromUid,toUid);
添加索引:
create index idx_account_place on tb_account using gist(place);
create index idx_uid on tb_account(uid);
查看索引:
select * from pg_indexes where tablename=’tbname’;
插入更新:
create unique index uix_user_page on user_pages(user_id,page_id);
INSERT INTO user_pages (user_id, page_id, enabled) VALUES (1, 1, TRUE) ON CONFLICT (user_id, page_id) DO UPDATE SET enabled = EXCLUDED.enabled;
excluded代表的是本要插入的值。
如果要将数值+1,使用以下方式:
insert into tb_viewed_records(
fromUid,
toUid,
count,
createTime,
lastUpdateTime
)
values (
#{fromUid},
#{toUid},
#{count},
#{createTime},
#{lastUpdateTime}
)
on conflict (fromUid, toUid) do update set
count = tb_viewed_records.count + 1, lastUpdateTime = #{lastUpdateTime}
实际操作:
insert into tb_account_private(
uid,wechat,aboutSex,aboutLove,demand,position,car,house,createTime,lastUpdateTime
)
values (
#{uid},#{wechat},#{aboutSex},#{aboutLove},#{demand},#{position},#{car},#{house},NOW(),
NOW()
)
on conflict (uid) do update set
lastUpdateTime = NOW()
查看表结构:
\d table
插入后获取自动生成的主键。设置useGeneratedKeys参数值为true,在执行添加记录之后可以获取到数据库自动生成的主键ID。
