2011-12-03 60 views
2

我想將匹配結果存儲在數據庫中。我有一個球員表,其中包含一個ID,名稱密碼。另一個存儲匹配的表格。然後最後一個匹配參與者表將有一個id,player_id(外鍵),match_id(外鍵)和一個score這是一個整數。我正在嘗試創建Match表,以便它可以引用兩個Match參與者,但我不確定如何執行此操作。sqlite數據庫中的兩個表引用android

代碼我已經做了所有具有兩個鏈接到同一個表創建表

myDB.execSQL("CREATE TABLE IF NOT EXISTS " 
        + playerTableName 
        + " (Player_id integer primary key autoincrement, " + 
      "UserName VARCHAR, Password VARCHAR, Experience INTEGER, Rating INTEGER);"); 

      myDB.execSQL("CREATE TABLE IF NOT EXISTS " 
        + matchTableName 
        + "(Match_id integer primary key autoincrement, " + 
      "? not sure here");"); 

      myDB.execSQL("CREATE TABLE IF NOT EXISTS " 
        + participantTableName 
        + "(Participant_id integer primary key autoincrement, " + 
        "player_id INTEGER, match_id Integer," + 
        "FOREIGN KEY(player_id) REFERENCES "+ playerTableName+"(Player_id)," + 
        " FOREIGN KEY(match_id) REFERENCES "+ matchTableName+"(Match_id)," + 
      " Score INTEGER);"); 

回答

1
myDB.execSQL("CREATE TABLE IF NOT EXISTS " 
       + matchTableName 
       + "(Match_id integer primary key autoincrement, " 
       + "Participant1_id integer, "); 
       + "Participant2_id integer, "); 
       + "FOREIGN KEY(Participant1_id) REFERENCES "+ participantTableName+"(Participant_id)," 
       + "FOREIGN KEY(Participant2_id) REFERENCES "+ participantTableName+"(Participant_id)" 
       + ");"; 

有沒有問題。當您執行查詢來選擇或插入時,請確保將正確的ID保存在您的表中,並且這將起作用。

一些注意事項:

  • 無需在參與者表的match_id。這隻會複製匹配表中的參與者ID。在SQL表中存在重複信息永遠不會有好處,它們可能不同步,並且約束可能會變成地獄(刪除時)。或者如果您想保留match_id,則不需要匹配表中的兩個participant_id。

  • 你應該名都主IDS _id,它與SQLite平時的好習慣(我認爲在某些情況下,Android的/ SQLite的會崩潰時,它不容易找到他們)