0

Given following schema:

document(id, path);
term(id, description);
term_document(id_term,id_document,frequency);

Given a document path and term description, if I don't have a record of the term and the document in the table term_documento I want to insert into the table term_document with frequency = 1, otherwise, I want to just increment the frequency value.

What I came up so far is this:

insert into term_document(id_term, id_document, frequency)
select term.id, document.id, 1
from term, document where term.description='to' and document.path='/home/rogger/Projetos/projeto-ori-ufu/src/main/resources/d1.txt'

which satisties the case I dont have a record in term_document, but I don't know how to increment to satisfy both.

2
  • This is the reoccuring topic of sequences per id. If you have concurrent write access, the best answer is: don't. See stackoverflow.com/a/24918964/939860 Commented May 7, 2017 at 18:57
  • good point @ErwinBrandstetter, however is a very simple application and I wont have concurrent access to my database. Commented May 7, 2017 at 19:16

1 Answer 1

1

Assuming you have a unique constraint on term_document(id_term, id_document), you can use on conflict clause in your insert:

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;

I used cross join as you did (only in modern syntax). If there is actually a relation between the two table, you'd need to join them on those columns instead.

Sign up to request clarification or add additional context in comments.

1 Comment

Note that INSERT...ON CONFLICT is only available in Postgres 9.5+.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.