0
点赞
收藏
分享

微信扫一扫

开发过程中PostgreSQL常用的SQL语句,持续更新ing

高子歌 03-28 08:00 阅读 3

修改字段类型

-- ALTER TABLE 模式名.表明 ALTER COLUMN 字段名 TYPE 类型;
alter table alarm.alarm_produce_config alter column alarm_level type int4;

重置序列值

-- ALTER SEQUENCE 序列名 RESTART WITH 序列值;
alter sequence enterprise_type_id_seq restart with 1;

查询表的字段名

-- SELECT COLUMN_NAME FROM information_schema.columns WHERE table_schema = '模式名' AND table_name = '表名';
select COLUMN_NAME from information_schema.columns where table_schema= 'safety' and table_name= 'alarm_record';

字段重命名

-- ALTER TABLE 模式名.表明 RENAME 字段名 TO 新字段名;
alter table archive.park_department rename "park_code" to "department_code";

删除表字段

-- ALTER TABLE 模式名.表明 DROP COLUMN IF EXISTS 字段名;
alter table forest.dict_fire_type drop column if exists color;

新增表字段

-- ALTER TABLE 模式名.表明 ADD COLUMN IF NOT EXISTS 字段名 字段类型;
alter table alarm.alarm_task_data add column if not exists alarm_id varchar(255);

删除不为空约束段

-- ALTER TABLE 表名 ALTER COLUMN 列名 DROP NOT NULL;
alter table emergency.alarm_record alter column level drop not null;

Mybatis XML中 > < >= <= 的写法

符号写法
<&lt;
>&gt;
<=&lt;=
>=&gt;=

命令行连接数据库

-- psql -U 用户名 -d 数据库
psql -U ltfse -d ltfse

查询表字段类型

-- 指定表明即可
SELECT column_name, data_type FROM information_schema.columns WHERE table_name = '表名';

为字段设置默认值

-- ALTER TABLE 表名 ALTER COLUMN 字段名 SET DEFAULT 默认值;
ALTER TABLE "safety"."point" ALTER COLUMN offline_alarm SET DEFAULT true;

删除字段默认值

-- ALTER TABLE 表名 ALTER COLUMN 字段名 DROP DEFAULT;
ALTER TABLE "safety"."point" ALTER COLUMN data_alarm DROP DEFAULT;

数组字段添加值

-- UPDATE 表名 SET 字段名 = array_append(字段名, '需要添加的值') WHERE 条件;
-- 请注意,在使用array_append函数时,如果字段原先没有值或者为NULL,则会创建一个只包含一个元素的新数组。如果字段已有值,则会在其后追加新元素。
UPDATE users SET interests = array_append(interests, 'sports') WHERE id = 1;

-- 如果您想要将多个值添加到数组中,可以使用array_cat函数,在这个例子中,||是用来连接两个数组的运算符。左边是现有的数组,右边是要追加的新元素数组。
UPDATE users SET interests = interests || '{sports,technology}' WHERE id = 1;

修改JsonB字段中的某个字段值

-- UPDATE 表名 SET JsonB字段名 = jsonb_set(JsonB字段名, '{要修改的字段}', '值') where Conditions
UPDATE safety.work_process SET basic_information_json = jsonb_set(basic_information_json, '{video}', '${val}') where work_no = 'ZK-001';

修改JsonB类型字段中的数组字段

-- 例如:现有一个work_process表,其中有一个字段(basic_information_json)的类型为JsonB,并且其中有一条数据该字段的值为:
-- {"level": "特级", "height": "1111", "spBill": [{"no": "ZK-DH-20240001", "workType": 3}], "workContent": "驳回状态"},
-- 现有一个需求需要向该字段中的spBill字段增加一个元素,那么我们就可以使用下面的sql来完成该需求

-- UPDATE my_table SET json_data = jsonb_set(json_data, '{my_array}', jsonb_insert(json_data->'my_array', '{-1}', '"new_element"'::jsonb)) WHERE Conditions
-- {-1}表示在索引末尾查询,如果需要在首位插入使用{0}即可

UPDATE work_process SET basic_information_json = jsonb_set(basic_information_json, '{spBill}',
    jsonb_insert(basic_information_json -> 'spBill', '{-1}', '{"no": "ZK-DH-20240001","workType": 3}'::jsonb)
) WHERE work_no = 'ZK-002';

PS:持续更新中。。。。

举报

相关推荐

0 条评论