我正在使用Sqlite 3.7.11和Windows x64 Visual Studio 2010.下面的示例可以从sqlite3.exe工具运行。我从代码中得到了相同的失败。
鉴于此表:
PRAGMA foreign_keys=ON;
CREATE TABLE hashes( id INTEGER PRIMARY KEY, hash CHARACTER(4) NOT NULL UNIQUE );
CREATE TABLE sources( id INTEGER PRIMARY KEY, source VARCHAR(64) NOT NULL UNIQUE );
CREATE TABLE files( hash_id INTEGER, source_id INTEGER, filename VARCHAR(2048), extension VARCHAR(16),
FOREIGN KEY(hash_id) REFERENCES hashes(id)
FOREIGN KEY(source_id) REFERENCES sources(id)
UNIQUE( hash_id, source_id, filename ) );
这个初始数据:
INSERT INTO hashes VALUES( ?, "abcd" );
INSERT INTO sources VALUES( ?, "mysource" );
我正在添加这样的行。文件表根据上述约束引用哈希表和源表。
INSERT INTO files ( hash_id, source_id, filename, extension )
SELECT hashes.id, sources.id, "filename.ext", "ext"
FROM hashes, sources
WHERE hashes.hash = "abcd" AND sources.source = "mysource";
一切正常,直到“id”出现在文件名或扩展名字段中。这没有任何意义 - 引用它。这两个插入都将失败:
INSERT INTO files ( hash_id, source_id, filename, extension )
SELECT hashes.id, sources.id, "id", ""
FROM hashes, sources
WHERE hashes.hash = "abcd" AND sources.source = "mysource";
INSERT INTO files ( hash_id, source_id, filename, extension )
SELECT hashes.id, sources.id, "filename.id", "id"
FROM hashes, sources
WHERE hashes.hash = "abcd" AND sources.source = "mysource";
错误:列名不明确:id
我是否需要以某种方式进一步逃避引用的值?
答案 0 :(得分:2)
嗯......这是一个菜鸟的错误。一旦我使用单引号来表示字符串文字,这就可以了:
INSERT INTO files ( hash_id, source_id, filename, extension )
SELECT hashes.id, sources.id, "id", ""
FROM hashes, sources
WHERE hashes.hash = "abcd" AND sources.source = "mysource";
INSERT INTO files ( hash_id, source_id, filename, extension )
SELECT hashes.id, sources.id, 'filename.id', 'id'
FROM hashes, sources
WHERE hashes.hash = "abcd" AND sources.source = "mysource";