简体   繁体   中英

union table, change serial primary key, postgresql

Postgresql:

I have two tables 'abc' and 'xyz' in postgresql. Both tables have same 'id' columns which type is 'serial primary key;'. abc table id column values are 1,2,3 and also xyz id column containing same values 1,2,3,4 I want to union both tables with 'union all' constraint. But I want to change 'xyz' id column values to next value of 'abc' id column last value as 1,2,3,4,5,6,7

select id from abc
union all
select id from xyz

|id|
 1
 2
 3
 1
 2
 3
 4

my wanted resuls as
|id|
 1
 2
 3
 4
 5
 6
 7

BETTER - Thanks to @CaiusJard This should do it for you

select id FROM abc 
UNION ALL select x.id + a.maxid FROM xyz x, 
(SELECT MAX(id) as maxid from abc) a
ORDER BY id

For anyone who's doing something like this:

I had a similar problem to this, I had table A and table B which had two different serials. My solution was to create a new table C which was identical to table B except it had an "oldid" column, and the id column was set to use the same sequence as table A. I then inserted all the data from table B into table C (putting the id in the oldid field). Once I fixed the refernces to point to from the oldid to the (new)id I was able to drop the oldid column.

In my case I needed to fix the old relations, and needed it to remain unique in the future (but I don't care that the ids from table A HAVE to all be before those from table C). Depending on what your trying to accomplish, this approach may be useful.

If anyone is going to use this approach, strictly speaking, there should be a trigger to prevent someone from manually setting an id in one table to match another. You should also alter the sequence to be owned by NONE so it's not dropped with table A, if table A is ever dropped.

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