简体   繁体   中英

SQLite create a new record if it doesn't exist

Hey so I'm trying to create a new record based on one which already exists, but I'm having trouble ensuring that this record doesn't already exist. The database stores details of transactions and has a field for whether it repeats.

I'm generating the new dates using

SELECT datetime(transactions.date, '+'||repeattransactions.interval||' days') 
AS 'newdate' FROM transactions, repeattransactions WHERE 
transactions.repeat = repeattransactions.id

Initially I'd like to use SELECT instead of INSERT just for debugging purposes. I've tried to do something with GROUP BY or COUNT(*) but the exact logic is eluding me. So for instance I've tried

SELECT * FROM transactions, (SELECT transactions.id, payee, category, amount, 
fromaccount, repeat, datetime(transactions.date, 
'+'||repeattransactions.interval||' days') AS 'date' FROM transactions,
repeattransactions WHERE transactions.repeat = repeattransactions.id)

but this obviously treats the two tables as though they were joined, it doesn't append the records to the bottom of the table which would let me group.

I've been struggling for days so any help would be appreciated!

EDIT: The docs say "The ON CONFLICT clause applies to UNIQUE and NOT NULL constraints". I can't have a unique constraint on the table by definition as I have to create the exact same record for a new transaction with just a new date. Or have I misinterpreted this?

EDIT2:

id        payee     repeat      date
1         jifoda    7           15/09/2011
2         jifoda    7           22/09/2011  <-- allowed as date different within subset
3         grefa     1           15/09/2011  <-- allowed as only date is not-unique
4         grefa     1           15/09/2011  <-- not allowed! exactly same as id 3

SQLite has special DDL statement for duplicates. Like:

create table test(a TEXT UNIQUE ON CONFLICT IGNORE);
insert into test values (1);
insert into test values (1);
select count(*) from test;
1

It can be also ON CONFLICT REPLACE . See docs.

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