两个引用sqlite数据库android中的表

时间:2011-12-03 23:26:11

标签: android sqlite

我正在尝试将匹配结果存储在数据库中。我有一个播放器表,其中包含一个id,名称密码。存储匹配的另一个表。最后是一个Match参与者表,它将包含idplayer_id(外键),match_id(外键)和score,它是一个整数。我正在尝试创建Match表,以便它可以引用两个Match参与者,但我不确定如何执行此操作。

我已经完成了创建表的代码

 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 个答案:

答案 0 :(得分: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。

  • 您应该为所有主要ID _id命名,这是SQLite通常的良好做法(我认为在某些情况下,Android / SQLite会在找不到它们时崩溃)