Postgresql使用技巧

    • 1.递归层次查询
    • 2.重复数据过滤
    • 3.COALESCE滤空处理
    • 4.日期、字符转换函数
    • 5.case when条件判断
    • 6.like模糊查询
    • 7.json中作为查询条件及只显示json中相应的key
    • 8.mybatis调用存储过程
    • 9.插入数组字段
    • 10.插入jsonb字段
    • 11.创建表序列技巧
    • 12.聚合函数string_agg与array_agg
    • 13.查询序列值
    • 14.增加修改列
    • 15.数据列联表更新

1.递归层次查询

  • 例:查询代理商及下属代理商
WITH RECURSIVE res AS (
    SELECT
        A .agent_id
    FROM
        AGENT.AGENT A
    WHERE
        A .agent_id = 620
    UNION ALL
        SELECT
            b.agent_id
        FROM
            AGENT.AGENT b,
            res
        WHERE
            b.parent_agent_id = res.agent_id
) SELECT
    agent_id
FROM
    res
  • 指定查询字段
WITH RECURSIVE res (
    agent_id,
    parent_agent_id,
    agent_name,
    remark,
    email,
    warn
) AS (
    SELECT
        A .agent_id,
        A .parent_agent_id,
        A .agent_name,
        A .remark,
        A .email,
        A .warn
    FROM
        AGENT.AGENT A
    WHERE
        A .agent_id = 620
    UNION ALL
        SELECT
            b.agent_id,
            b.parent_agent_id,
            b.agent_name,
            b.remark,
            b.email,
            b.warn
        FROM
            AGENT.AGENT b,
            res
        WHERE
            b.parent_agent_id = res.agent_id
) SELECT
    agent_id,
    parent_agent_id,
    agent_name,
    remark,
    email,
    warn
FROM
    res
ORDER BY
    agent_id ASC

2.重复数据过滤

SELECT
    *
FROM
    estate.room A
WHERE
    ctid != (
        SELECT
            MAX (ctid)
        FROM
            estate.room b
        WHERE
            A .unit_id = b.unit_Id
        AND A .room_number = b.room_number
    );

3.COALESCE滤空处理

SELECT
    COALESCE (MAX(sort_num), 0) + 1 AS maxnum
FROM
    estate.unit
WHERE
    building_id = 11

4.日期、字符转换函数

  • to_date,to_char类似oracle

5.case when条件判断

case  dep."type" when 7 then true else false end as isSign

6.like模糊查询

and dept_name like CONCAT('%',#{depName},'%')  

7.json中作为查询条件及只显示json中相应的key

SELECT
    A .subsql -> 'ver' AS ver,
    A .subsql
FROM
    (
        SELECT
            guid,
            jsonb_pretty (config :: jsonb),
            jsonb_array_elements (config :: jsonb -> 'expands') AS subsql
        FROM
            log."ConfigLog"
    ) A
--WHERE
--  A .subsql @> '{"type":2,"name":"刷卡器"}' :: jsonb
LIMIT 10;
SELECT
    A .subsql -> 'ver' AS ver,
    A .subsql
FROM
    (
        SELECT
            guid,
            jsonb_pretty (config :: jsonb),
            jsonb_array_elements (config :: jsonb -> 'expands') AS subsql
        FROM
            log."ConfigLog"
    ) A
WHERE
    --条件 json字段包含"type":2,"name":"刷卡器"的数据
    A .subsql @> '{"type":2,"name":"刷卡器"}' :: jsonb
LIMIT 10;

8.mybatis调用存储过程

   int bindRoomWithManagementAndDoor(@Param("map") Map<String, Object> map, @Param("deviceIds") List<Integer> deviceIds);

  <select id="bindRoomWithManagementAndDoor" resultType="java.lang.Integer">
    SELECT * FROM device.new_wy_manage_device_bind(#{map.depId,jdbcType=INTEGER},
    #{map.managementGuid,jdbcType=VARCHAR}, #{map.managementName,jdbcType=VARCHAR},
    #{map.roomId,jdbcType=INTEGER}, #{map.unitId,jdbcType=INTEGER}, #{map.buildingId,jdbcType=INTEGER},
    <foreach collection="deviceIds" item="deviceId" index="index" open="ARRAY[" close="]" separator=",">
      #{deviceId}
    foreach>
    )
  select>
 

9.插入数组字段

<result column="devices" property="devices" javaType="java.lang.Integer" typeHandler="com.doordu.soa.service.comm.hadler.ArrayTypeHandler"/>
"devices" int4[],
 #{devices,typeHandler=com.doordu.soa.service.comm.hadler.ArrayTypeHandler}::int4[],

10.插入jsonb字段

<result column="id_pay_rule" property="idPayRule" jdbcType="OTHER" />

   #{idPayRule,jdbcType=OTHER}::jsonb,        

Json格式

11.创建表序列技巧

serial PRIMARY KEY
DROP TABLE "device"."camera";
CREATE TABLE "device"."camera" (
    "camera_id" serial PRIMARY KEY,
    "camera_name" VARCHAR (200) COLLATE "default" NOT NULL,
    "serial_number" VARCHAR (200) COLLATE "default" NOT NULL,
    "brand_id" int2 DEFAULT 0 NOT NULL,
    "create_user" int4 DEFAULT 0 NOT NULL,
    "create_time" TIMESTAMP (0) DEFAULT (now()) :: TIMESTAMP (0) WITHOUT TIME ZONE
);

ALTER TABLE "device"."camera" OWNER TO "ddpguser";

COMMENT ON COLUMN "device"."camera"."camera_id" IS '主键';

COMMENT ON COLUMN "device"."camera"."camera_name" IS '相机名';

COMMENT ON COLUMN "device"."camera"."serial_number" IS '序列号';

COMMENT ON COLUMN "device"."camera"."brand_id" IS '品牌';

COMMENT ON COLUMN "device"."camera"."create_user" IS '创建人';

COMMENT ON COLUMN "device"."camera"."create_time" IS '创建时间';

12.聚合函数string_agg与array_agg

https://blog.csdn.net/u011944141/article/details/78902678
array_agg(expression)
把表达式变成一个数组 一般配合 array_to_string() 函数使用
string_agg(expression, delimiter)
直接把一个表达式变成字符串

CREATE SCHEMA jinbo;
CREATE TABLE jinbo.employee (
    empno SMALLINT,
    ename VARCHAR (20),
    job VARCHAR (20),
    mgr SMALLINT,
    hiredate DATE,
    sal BIGINT,
    comm BIGINT,
    deptno SMALLINT
);
INSERT INTO jinbo.employee (
    empno,
    ename,
    job,
    mgr,
    hiredate,
    sal,
    comm,
    deptno
)
VALUES
    (
        7499,
        'ALLEN',
        'SALEMAN',
        7698,
        '2014-11-12',
        16000,
        300,
        30
    );

INSERT INTO jinbo.employee (
    empno,
    ename,
    job,
    mgr,
    hiredate,
    sal,
    comm,
    deptno
)
VALUES
    (
        7499,
        'ALLEN',
        'SALEMAN',
        7698,
        '2014-11-12',
        16000,
        300,
        30
    );

INSERT INTO jinbo.employee (
    empno,
    ename,
    job,
    mgr,
    hiredate,
    sal,
    comm,
    deptno
)
VALUES
    (
        7654,
        'MARTIN',
        'SALEMAN',
        7698,
        '2016-09-12',
        12000,
        1400,
        30
    );
  • 1.查询同一个部门下的员工且合并起来
    方法1:
select deptno, string_agg(ename, ',') from jinbo.employee group by deptno;

 deptno |  string_agg  
--------+--------------
     20 | JONES
     30 | ALLEN,MARTIN

方法2:

select deptno, array_to_string(array_agg(ename),',') from jinbo.employee group by deptno;
 deptno | array_to_string 
--------+-----------------
     20 | JONES
     30 | ALLEN,MARTIN
  • 2、在1条件的基础上,按ename 倒叙合并
select deptno, string_agg(ename, ',' order by ename desc) from jinbo.employee group by deptno;
3、 deptno |  string_agg  
4、--------+--------------
5、     20 | JONES
6、     30 | MARTIN,ALLEN
  • 3、按数组格式输出使用 array_agg
select deptno, array_agg(ename) from jinbo.employee group by deptno;
 deptno |   array_agg    
--------+----------------
     20 | {JONES}
     30 | {ALLEN,MARTIN}
  • 4、array_agg 去重元素,例如查询所有的部门
select array_agg(distinct deptno) from jinbo.employee;
array_agg 
-----------
 {20,30}
(1 row)

不仅可以去重,还可以排序

select array_agg(distinct deptno order by deptno desc) from jinbo.employee;
 array_agg 
-----------
 {30,20}
(1 row)

13.查询序列值

select nextval('log.admin_operation_log_id_seq')

14.增加修改列

ALTER TABLE "report"."tunan_fwxxz"
ADD COLUMN "update_time" timestamp DEFAULT now()::timestamp(0) without time zone;

alter table  report.ut_estate alter  COLUMN  mpmc  type varchar(100) ; 

15.数据列联表更新

update report.ut_estate a set jwh=b.jwhmc from estate.panyu_jwh b where a.jwhdm=jwhbm;

你可能感兴趣的:(服务器架构/运维)