简体   繁体   中英

How to increase sequence only if column's value is different from the previous? PostgreSQL

Exactly as in the topic. For really easy example I have table:

Cars(
    TEXT make,
    INTEGER value,
    TEXT owner
);

With records like this:

('BMW', 100000, 'AcmeCompany')
('BMW', 350000, 'XCompany')
('Lamborgini', 500000, 'YCompany')
('Fiat', 30000, 'ZCompany')
('BMW', 200000, 'XCompany')

and I want to create table with column makeID (don't ask why, it's just a example :P)

Informations(
    INTEGER makeID
    other_stuff
)

I have sequence on makeID and I have to increment sequence ONLY when I have new value of make in in my SELECT (it's like transtalion from string into integer; if it is possible I don't wanna sha1 or other cryptografic things just a simply sequence!)

   INSERT INTO Informations(makeID) ( 
        -- IF I have new value: SELECT nextVal('mysequence')
        -- ELSE : SELECT currval('mysequence')
   )

I know it should be possible by pgsql function (sort table by 'make' column, then save last value of 'make' into temp variable and do INSERT INTO with check value of my actual 'make' value with value in temp for incrementing sequence variable or not). But there is easier way, just by query? Combination of join, sort and distinct?

Not sure I understand. It would be simply serial with select distinct

create table make (
    make_id serial,
    make_brand text,
    make_owner text
);
insert into make (make_brand, make_owner)
select distinct make, owner
from cars;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM