sql - How to optimize this huge and ugly query, ignoring duplicates? -
i'm not sql expert, here sqlite query on table "query" (key: systemid, topicid, documentid, foreign keys) gets foreign keys , insert avoiding duplicates. huge, ugly , have execute thousands of times:
command.commandtext = "insert query (systemid, topicid, documentid) " + "(select id system tag = @systemtag collate nocase), " + "(select id topic number = @topicnumber collate nocase), " + "(select id document number = @docnumber collate nocase) " + "where not exists (select 1 query " + "systemid = (select id system tag = @systemtag) , " + "topicid = (select 1 topic number = @topicnumber) , " + "documentid = (select id document number = @docnumber))"; question: way tell sql "don't worry duplicates, ignore insert statement". or maybe using variables/temporary tables, ad statements?
edit: straight query:
insert query (systemid, topicid, documentid) (select id system tag = @systemtag collate nocase), (select id topic number = @topicnumber collate nocase), (select id document number = @docnumber collate nocase) not exists (select 1 query systemid = (select id system tag = @systemtag) , topicid = (select 1 topic number = @topicnumber) , documentid = (select id document number = @docnumber));
to prevent inserting duplicate, need 2 things:
a table definition identifies columns needing unique. example:
create table query ( systemid integer, topicid integer, documentid integer, primary key (systemid, topicid, documentid)); or
create table query ( systemid integer, topicid integer, documentid integer, primary key (systemid, topicid, documentid)); and conflict clause. can in 1 of 2 ways, either in table definition (leaving above make default ignore, pretty want), or in insert command:
insert or ignore query... if have table setup unique constraint, don't need change insert query (besides removing admittedly ugly where not exists bit.
the drawback yes, make code attempt sorts of insertions , fail. @ other way: makes database behave way want behave. , key in working databases, don't want have full manual scan of tables when you're doing operation. want let database dirty work.
Comments
Post a Comment