更新POSTGRESQL中的数据类型后重置自动递增序列

时间:2018-02-14 10:05:36

标签: postgresql auto-increment

我有两个现有的表DOS_PROFILE和DOS,

CREATE TABLE DOS_PROFILE
(
DOS_PROFILE_ID uuid DEFAULT uuid_generate_v4 (),
PAT_ID VARCHAR NOT NULL,
PRODUCT_ID VARCHAR NOT NULL,
REMINDER_TIME VARCHAR,
DOS_SETUP_DATE BIGINT,
TIME_ZONE VARCHAR NOT NULL, 
IS_ACTIVE BOOLEAN NOT NULL,
PRIMARY KEY (DOS_PROFILE_ID)
);

CREATE TABLE DOS
 (
 DOS_ID uuid DEFAULT uuid_generate_v4 (),
 DOS_NUMBER INTEGER,
 DOS_DATE BIGINT NOT NULL,
 DOS_STATUS VARCHAR NOT NULL,
 DOS_PROFILE_ID uuid NOT NULL,
 PRIMARY KEY (DOS_ID),
 FOREIGN KEY (DOS_PROFILE_ID) REFERENCES DOS_PROFILE(DOS_PROFILE_ID)
  ); 

示例数据: DOS

'e5d7b7c2-af76-41b2-80d7-d68bdd4ad596',0,'1483268400000','taken','7e28dc41-2f4b-43d5-9291-3ac147ebbac8'
'62b2e7ff-618a-42c4-a09e-df52dffaeaec',0,'1484478000000','not_logged','7e28dc41-2f4b-43d5-9291-3ac147ebbac8'
'421387af-fbbb-49c6-abd1-a523fec02fbf',0,'1518546600000','taken','d833fcae-d98c-4314-857b-51098075c2da'
'ca6524d5-32f9-4b74-bfaa-a39ce5b92bf1',0,'1518546600000','taken','0e826fc4-09e7-4c83-941e-c9c547fa515f'
'7945c8a5-7d67-4c9d-b67f-065e9282623b',0,'1518546600000','taken','6c15cba5-bbcb-4fba-82d5-a6dbefa3b455'

DOS_PROFILE

'7e28dc41-2f4b-43d5-9291-3ac147ebbac8','1283364','poi','03:30','1516359600000','Pacific/Samoa',false
'd833fcae-d98c-4314-857b-51098075c2da','1283364','poi','18:40','1518546600000','Asia/Kolkata',false
'0e826fc4-09e7-4c83-941e-c9c547fa515f','1283364','poi','18:40','1518546600000','Asia/Kolkata',false
'6c15cba5-bbcb-4fba-82d5-a6dbefa3b455','1283364','poi','18:40','1518546600000','Asia/Kolkata',false
'04c15d61-d6fd-4754-ae65-7af8a1ec667e','1283364','poi','18:40','1518546600000','Asia/Kolkata',false

用于自动增量的序列:

CREATE SEQUENCE public.dos_dosNumber_seq
  INCREMENT 1
  MINVALUE 1
  MAXVALUE 9223372036854775807
  START 1
  CACHE 1;

为DOST表中为PRODUCT_ID =' poi'保存的所有现有行设置DOS_NUMBER。来自DOS_PROFILE。对于每个PAT_ID,DOS_NUMBER应以增量顺序从1开始;

我尝试了什么:

update DOS set dos_number = nextval('dos_dosNumber_seq') where dos_profile_id in 
    (select dos_profile_id from DOS_profile where pat_id = '1283364' and product_id='poi' 
     group by pat_id order by dos_setup_date);
ALTER SEQUENCE dos_dosNumber_seq RESTART WITH 1;

在上面的方法中,我需要使用单独的查询一次又一次地重置它,我必须在更新查询中显式指定pat_id。我需要通用更新并在同一查询中重置序列。

如果需要手术,那也没关系。 谢谢!

1 个答案:

答案 0 :(得分:0)

这是我能想到的,必须有一些优化的范围:

CREATE SEQUENCE public.dos_dosNumber_seq
  INCREMENT 1
  MINVALUE 1
  MAXVALUE 9223372036854775807
  START 1
  CACHE 1;

CREATE OR REPLACE FUNCTION updateDosNumber(i varchar(12)) RETURNS VOID AS $$
    BEGIN        
      update dos set dos_number = nextval('dos_dosNumber_seq') where dos_profile_id in 
    (select dos_profile_id from dos_profile where pat_id = i and product_id='taltz' 
      order by dos_setup_date);
     ALTER SEQUENCE dos_dosNumber_seq RESTART WITH 1;   

    END;
    $$ LANGUAGE plpgsql;

SELECT updateDosNumber(p.pat_id) from (select distinct pat_id from dos_profile) p ;