How to implement priorities in SQL (postgres)

后端 未结 2 537
挽巷
挽巷 2021-01-28 23:30

I\'m writing some software that requires storing items in a database, the items need to have a \'priority\' so we end up with

    ID  |  Name        |  Priority
         


        
2条回答
  •  野性不改
    2021-01-29 00:25

    Two updates in a single transaction should work fine on a such small table.

    create temp table priorities (
      id integer primary key,
      name varchar(15) not null,
      priority integer not null check (priority > 0 and priority < 100)
    );
    
    insert into priorities values 
    (1,'Pear',4),
    (2,'Apple',2),
    (3,'Orange',1),
    (4,'Banana',3);
    
    -- Make Pear priority 1.
    begin;
    update priorities 
    set priority = priority + 1
    -- The value below is the priority you're aiming for. You want
    -- Pear to be #1, so you use ">= 1".
    where priority >= 1;
    
    update priorities
    set priority = 1 where name = 'Pear';
    commit;
    

    For convenience, you can wrap this in a stored procedure.

提交回复
热议问题