插入SQLite中的联结表

时间:2012-11-09 20:41:29

标签: sqlite junction

我尝试了各种方法。这是对我有意义的,但是当我尝试执行insert into listsandplayers时,它告诉我没有列listID存在。我用insert into listsandplayers语句尝试了几个不同的东西并继续得到错误。

我已经在这里发布了我认为该声明应该最有效的方式。这是这里显示的最后一个陈述。

CREATE TABLE IF NOT EXISTS 
   lists (listID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, listName VARCHAR(30));

CREATE TABLE IF NOT EXISTS 
   players(playerID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, playerName VARCHAR);

CREATE TABLE IF NOT EXISTS 
    listsandplayers(listsandplayersID INTEGER NOT NULL, 
                    listID INTEGER REFERENCES lists (listID),  
                    playerID INTEGER REFERENCES players (playerID));

INSERT INTO lists (listName) VALUES('Los Angeles Dodgers');

INSERT INTO players (playerName) VALUES('Clayton Kershaw');

INSERT INTO listsandplayers (listID, playerID) VALUES(listID, playerID)   
WHERE listName = 'Los Angeles Dodgers'  
AND playerName = 'Clayton Kershaw'  
NATURAL JOIN lists  
NATURAL JOIN players;

1 个答案:

答案 0 :(得分:1)

这不是valid syntax for an INSERT command。 试试这个:

INSERT INTO ListsAndPlayers (ListsAndPlayersID, ListID, PlayerID)
VALUES (42,
        (SELECT ListID FROM Lists WHERE ListName = 'Los Angeles Dodgers'),
        (SELECT PlayerID FROM Players WHERE PlayerName = 'Clayton Kershaw'));

如果您已将ListsAndPlayersID列声明为INTEGER PRIMARY KEY,则SQLite会自动生成一个值。 (您也可以删除ListsAndPlayersID列,只使用ListIDPlayerID的组合作为主键。)