2012-11-09 90 views
1

我試過了各種方法。這是對我有意義的一個,但是當我嘗試執行insert into listsandplayers時,它告訴我沒有列listID存在。我用我的insert into listsandplayers聲明嘗試了幾個不同的事情,並繼續發生錯誤。插入到SQLite的聯結表中

我在這裏發佈了我的感受,聲明應該最好。這是這裏顯示的最後一個陳述。

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

這不是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')); 

如果你已經宣佈ListsAndPlayersIDINTEGER PRIMARY KEY時,SQLite會自動生成一個值。 (你也可以刪除ListsAndPlayersID柱,只是使用的ListID組合和PlayerID作爲主鍵。)

+0

啊我很抱歉,我不能相信我沒有定義listsandplayersID作爲主。謝謝。我也永遠不會使用select語句的值,我在想聯接。 – Jon