关联类SQLite表和外键

时间:2014-05-22 07:17:28

标签: android sql sqlite associations

如果我在两个多对多表之间有一个关联表,那么表格如下所示?:

实践:

private static final String CREATE_TABLE_PRACTICAL =
    "CREATE TABLE " + TABLE_PRACTICAL  + "(" +
        Practical_ID + " INTEGER NOT NULL PRIMARY KEY," +
        Start_Date + " DATE," +
        End_Date + " DATE," +
        Practical_Type + " STRING," +
        Practical_Topic + " STRING" +
    ");";

模块:

private static final String CREATE_TABLE_MODULE =
    "CREATE TABLE " + TABLE_MODULE + "(" +
        Module_Code + " STRING NOT NULL PRIMARY KEY," +
        Module_Name + " STRING," +
        Year_Level + " INTEGER," +
        Lecturer_Name + " STRING," +
        Lecturer_Email + " STRING" +
    ");";

ModulePrac:

private static final String CREATE_TABLE_PRAC_MODULES =
    "CREATE TABLE " + TABLE_PRAC_MODULES + "(" +
        Practical_ID + " INTEGER NOT NULL," +
        Module_Code + "STRING NOT NULL," +
        " FOREIGN KEY " + "(" + Practical_ID + ")" +
            "REFERENCES" + TABLE_PRACTICAL + "(" + Practical_ID + ")" +
        " FOREIGN KEY " + "(" + Module_Code + ")" +
            "REFERENCES" + TABLE_MODULE + "(" + Module_Code + ")" +
    ");";

或者PracModule表的密钥标识符应该是:

Practical_ID INTEGER NOT NULL REFERENCES Practicals(PracticalID),
ModuleCode INTEGER NOT NULL REFERENCES Module (ModuleCode),
PRIMARY KEY (PracticalID, ModuleCode)

不同的站点表示表的主键都是关联类的外键,而其他站点则表示它们都是外键和主键。我很困惑。

1 个答案:

答案 0 :(得分:0)

是否将这些外键约束写为表约束(如在CREATE_TABLE_PRAC_MODULES中)或列约束(如在上一个代码块中)都没有任何区别。 (将它们写为列约束通常更简单,但如果外键由多列组成,则需要表约束。)

唯一真正的区别是第二个代码块声明了主键。

主键也是(完全或部分)外键没有错,只要这正确描述了实体之间的实际关系。 在这种情况下,这似乎是正确的。