PostgreSQL 9.5 Insert data on a key with multiple occurences

时间:2017-08-04 12:06:02

标签: sql postgresql

I have 2 tables which are representing the same type of datas, one is in my DB and the other is coming from my client one's. Both his and my table are having some ID as PRIMARY KEY, but they are absolutely not related.

There is a field (field1) which is common between the two table, but this field is not always UNIQUE. In most cases, there are the same amount of tuples with this field in each table, but it is not necessary the case. Here is an example to illustrate the situation :

My table :

id_mytable    field1    field2  id_clients
1             aa1       null    null
2             aa1       null    null
3             aa1       null    null
4             aa2       null    null
5             aa2       null    null
6             aa3       null    null
7             aa4       null    null

And the client's table:

id_clients    field1    field2
9             aa1       value1
10            aa1       value2
11            aa2       value3
12            aa2       value4
13            aa2       value5
14            aa3       value6
15            aa4       value7

And the result I would like to get, sorted by the field1 :

id_mytable    field1    field2  id_clients
1             aa1       value1  9
2             aa1       value2  10
3             aa1       null    null
4             aa2       value3  11
5             aa2       value4  12
null          aa2       value5  13
6             aa3       value6  14
7             aa4       value7  15

You can notice the values not fulfilled in the result table where it was a difference betwenn my and the client's table, and that a new row was inserted. The idea is to be able to fulfill my table with the field2 and the id_clients. So far I cannot figure out a way to achieve that, my guess is that my relative beginner level makes me miss a DB's concept...

And here is an online sample, with the code proposed by ttallierchio : http://rextester.com/LOLH81061

Thank you very much for your attention.

2 个答案:

答案 0 :(得分:1)

You can use full outer join. The trick is calculating the new id:

select coalesce(mt.id,
                m.maxid + row_number() over (partition by mt.id order by ct.id)
               ) as newid
       mt.field1, ct.field2, ct.id
from mytable mt full outer join
     clienttable ct
     on mt.id = ct.id and mt.field1 = ct.field1 cross join
     (select max(id) as maxid from mytable) as m;

答案 1 :(得分:1)

you want to use a full outer join. the reason for this is you are not sure if data exists in either table so you want to combine and take data if exists in either one. i would just use row number to ensure uniqueness.

SELECT row_number() over(order by mt.field1),
   coalesce(mt.field1,c.field1) as field1,
   coalesce(mt.field2,c.field2) as field2,
   c.id as id_clients 
FROM mytable mt  
   FULL OUTER  JOIN clients c 
        on mt.id = c.id and c.field1 = mt.field1;