sql增量值,如果存在,否则插入值1

时间:2017-05-07 18:45:27

标签: sql database postgresql

给出以下架构:

_e()

鉴于文档document(id, path); term(id, description); term_document(id_term,id_document,frequency); 和字词path,如果我在表description中没有termdocument的记录我想在频率= 1的表term_documento中插入,否则,我只想增加term_document值。

我到目前为止所得到的是:

frequency

这使我在term_document中没有记录的情况,但我不知道如何增加以满足两者。

1 个答案:

答案 0 :(得分:1)

假设您对term_document(id_term,id_document)有唯一约束,则可以在插入中使用on conflict子句:

insert into term_document(id_term, id_document, frequency)
select t.id, d.id, 1
from term t
cross join document d
where t.description = 'to'
    and d.path = '/home/rogger/Projetos/projeto-ori-ufu/src/main/resources/d1.txt'
on conflict (id_term, id_document) do update set frequency = frequency + 1;

我使用了交叉连接(仅在现代语法中)。如果两个表之间实际存在关系,则需要在这些列上加入它们。