我对SQLite还是很陌生,并试图做一些看起来很简单但无法正常工作的事情。
我想在具有相同OwnerID但数据略有不同的表(部分副本)中插入一条新记录,因此插入记录数据;
2,55,newdata,DARLTY
原始记录数据在哪里;
1,55,originaldata,DARLTY
问题是我一直在'OwnerID'附近:语法错误。我想在将原始记录值插入新记录之前,需要以某种方式将其转换为变量,但是如何呢?
这就是我拥有的明显有缺陷的TIA
INSERT INTO MyTable
NULL AS KeyID, OwnerID AS OwnerID, 'newdata' AS Field2, Field3 AS Field3
WHERE Field3 LIKE '%DARL%'
AND Field3 <> 'DARLINGTON'
;
答案 0 :(得分:0)
您缺少 SELECT
和 FROM
关键字。
因此您的查询应该/应该是:-
INSERT INTO mytable
SELECT null AS keyid,ownerid AS ownerid,field2 AS field2,field3 AS field3
FROM mytable WHERE field3 LIKE '%DARLTY%' AND field3 <> 'DARLINGTON';
虽然稍微简单一些:-
INSERT INTO mytable (ownerid,field2,field3)
SELECT ownerid,field2,field3
FROM mytable WHERE field3 LIKE '%DARLTY%' AND field3 <> 'DARLINGTON';
会完全一样。
例如以下(为方便起见,在表名中添加了 x ):-
DROP TABLE IF EXISTS mytablex ;
CREATE TABLE IF NOT EXISTS mytablex (keyid INTEGER PRIMARY KEY,ownerid INTEGER, field2 TEXT, field3 TEXT);
INSERT INTO mytablex VALUES(1,55,'newdata','DARLTY'); -- Original value
INSERT INTO mytablex (ownerid,field2,field3)
SELECT ownerid,field2,field3
FROM mytablex WHERE field3 LIKE '%DARLTY%' AND field3 <> 'DARLINGTON';
SELECT * FROM mytablex;
结果:-
但是,当心,如果您随后运行插入操作,则会插入更多行,例如再次使用以下命令:-
INSERT INTO mytablex (ownerid,field2,field3)
SELECT ownerid,field2,field3
FROM mytablex WHERE field3 LIKE '%DARLTY%' AND field3 <> 'DARLINGTON';
SELECT * FROM mytablex;
将导致:-
如果第三次运行,则:-
为消除此类重复,您不妨考虑使用:-
INSERT INTO mytablex (ownerid,field2,field3) SELECT ownerid,field2,field3
FROM mytablex
WHERE field3 LIKE '%DARLTY%'
AND field3 <> 'DARLINGTON'
AND (
SELECT count() FROM mytablex WHERE field3 LIKE '%DARLTY%' AND field3 <> 'DARLINGTON'
) = 1;