这三个SQLITE INSERTS可以组合或改进吗?

时间:2011-02-21 16:39:32

标签: sql sqlite insert

我有三张桌子:

CREATE TABLE "local" ("id" INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL , "serialNumber" TEXT, "location" TEXT)

CREATE TABLE "setups" ("id" INTEGER PRIMARY KEY  NOT NULL ,"hold" TEXT,"mode" INTEGER,"setTemp" REAL,"maxSTemp" REAL,"minSTemp" REAL,"units" TEXT,"heat" INTEGER,"heatMode" INTEGER,"fanMode" INTEGER,"fan" INTEGER,"cool" INTEGER)

CREATE TABLE "data" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ,"humidity" REAL,"time" INTEGER,"filtChng" INTEGER,"indoorTemp" REAL,"outdoorTemp" REAL, "setups_id" INTEGER, "local_id" INTEGER)

每次我收到新条目时都会执行:

INSERT INTO local ('serialNumber') SELECT 'XXXX' WHERE NOT EXISTS (SELECT * FROM local WHERE serialNumber='XXXX')"

INSERT INTO setups ('hold','mode','setTemp','maxSTemp','minSTemp','units','heat','heatMode','fanMode','fan','cool') SELECT '00',1,74.0,74.0,74.0,'F',1,1,1,1,1 WHERE NOT EXISTS (SELECT * FROM setups WHERE hold='00' AND mode=1 AND setTemp=74.0 AND maxSTemp=74.0 AND minSTemp=74.0 AND units='F' AND heat=1 AND heatMode=1 AND fanMode=1 AND fan=1 AND cool=1)

 INSERT INTO data ('humidity','filtChng','time','indoorTemp','outdoorTemp',local_id,setups_id) SELECT 74.0,111111111,100,74.0,74.0,local.id,setups.id FROM local CROSS JOIN setups WHERE local.serialNumber='XXXX' AND setups.hold='00' AND setups.mode=1 AND setups.setTemp=74.0 AND setups.maxSTemp=74.0 AND setups.minSTemp=74.0 AND setups.units='F' AND setups.heat=1 AND setups.heatMode=1 AND setups.fanMode=1 AND setups.fan=1 AND setups.cool=1

我正在做的工作,但似乎很慢,多余/低效......

1 个答案:

答案 0 :(得分:0)

如果在“serialNumber”字段上使用唯一约束,则可以从“本地”插入中删除“where not exists”部分。注意,这将抛出约束违规而不是不插入行。所以一定要在应用程序中处理它。

虽然我认为是,但请确保在您的应用中确实需要检查重复项。