· 8 years ago · Jul 13, 2018, 03:36 PM
1drop table if exists tt_t;
2create temp table tt_t(id serial primary key, main_id int, external_id int);
3
4insert into tt_t(main_id, external_id)
5select currval(pg_get_serial_sequence('tt_t', 'id')), 1
6where not exists (select from tt_t where external_id = 1);
7
8do
9$$
10begin
11 if not exists(select from tt_t where external_id = 1)
12 then
13 insert into tt_t(external_id, main_id)
14 values(1, currval(pg_get_serial_sequence('tt_t', 'id')));
15 end if;
16end;
17$$
18;
19
20insert into tt_t(id, main_id, external_id)
21select nextval(pg_get_serial_sequence('tt_t', 'id')), currval(pg_get_serial_sequence('tt_t', 'id')), 1
22where not exists (select from tt_t where external_id = 1);