我不是SQL專家,這是我對錶「查詢」(鍵:SystemId,TopicId,DocumentId,所有也是外鍵)我的SQLite查詢獲取外鍵和插入避免重複。但它是巨大的,醜陋的,我要執行它上千次:如何優化這個龐大而醜陋的查詢,忽略重複?
command.CommandText = "INSERT INTO Query (SystemId, TopicId, DocumentId) " +
"(SELECT Id FROM System WHERE Tag = @SystemTag COLLATE NOCASE), " +
"(SELECT Id FROM Topic WHERE Number = @TopicNumber COLLATE NOCASE), " +
"(SELECT Id FROM Document WHERE Number = @DocNumber COLLATE NOCASE) " +
"WHERE NOT EXISTS (SELECT 1 FROM Query WHERE " +
"SystemId = (SELECT Id FROM System WHERE Tag = @SystemTag) AND " +
"TopicId = (SELECT 1 FROM Topic WHERE Number = @TopicNumber) AND " +
"DocumentId = (SELECT Id FROM Document WHERE Number = @DocNumber))";
問題:沒有辦法告訴SQL「不用擔心重複,忽略INSERT語句」。或者可能使用變量/臨時表,AD語句?
編輯:直查詢:
INSERT INTO Query (SystemId, TopicId, DocumentId)
(SELECT Id FROM System WHERE Tag = @SystemTag COLLATE NOCASE),
(SELECT Id FROM Topic WHERE Number = @TopicNumber COLLATE NOCASE),
(SELECT Id FROM Document WHERE Number = @DocNumber COLLATE NOCASE)
WHERE NOT EXISTS (SELECT 1 FROM Query WHERE
SystemId = (SELECT Id FROM System WHERE Tag = @SystemTag) AND
TopicId = (SELECT 1 FROM Topic WHERE Number = @TopicNumber) AND
DocumentId = (SELECT Id FROM Document WHERE Number = @DocNumber));
這在使用SELECT的INSERT中,我需要避免重複... – gremo 2010-12-03 10:05:18