2017-05-07 13 views
0

を考えると、次のスキーマ:SQL増分値1

私は termの記録やテーブル term_documentodocumentを持っていない場合は、文書 path用語 description考える
document(id, path); 
term(id, description); 
term_document(id_term,id_document,frequency); 

私は周波数= 1のテーブルterm_documentに挿入したいのですが、それ以外の場合は、frequencyの値を増やしたいだけです。私がこれまでやってき何

はこれです:

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' 

私はterm_documentのレコードを持っていけない場合をsatistiesが、私は両方を満たすためにインクリメントする方法がわからないもの。

+0

これは、idごとのシーケンスの再作成のトピックです。並行書き込みアクセス権を持っている場合、最善の答えは、そうではありません。 http://stackoverflow.com/a/24918964/939860 –

+0

良い点@ErwinBrandstetterを参照してください、しかし、非常に簡単なアプリケーションであり、私は自分のデータベースに同時にアクセスするつもりはありません。 –

答えて

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; 

私はクロスはあなたが(だけ近代的な構文で)行ったように参加しました。実際に2つのテーブルの間に関係がある場合は、代わりにそれらの列にそれらを結合する必要があります。

+0

INSERT ... ON CONFLICTはPostgreSQL 9.5以降でのみ利用可能です。 –