如何在SQLite中创建外键

时间:2014-03-19 22:20:11

标签: android sqlite

在SQLite中创建表时,是否可以按如下方式编写外键?

// income table create statement

private static final String CREATE_TABLE_income = "CREATE TABLE " + TABLE_income
        + "(" + KEY_IID + " INTEGER PRIMARY KEY," + KEY_AMOUNT + " TEXT," +KEY_ID + " INTEGER FOREIGN KEY REFERENCES TABLE_user(uid)" 
        + KEY_INCOMEDATE + " DATETIME" +KEY_INCOMETYPE + " TEXT" + ")";

2 个答案:

答案 0 :(得分:1)

你应该把你的外键定义放在列列表的末尾:

private static final String CREATE_TABLE_income = "CREATE TABLE " + TABLE_income
        + "(" + KEY_IID + " INTEGER PRIMARY KEY," + KEY_AMOUNT + " TEXT," +KEY_ID + " INTEGER," 
        + KEY_INCOMEDATE + " DATETIME," + KEY_INCOMETYPE + " TEXT, "
        +"FOREIGN KEY (" + KEY_ID + ") REFERENCES TABLE_user(uid))";

答案 1 :(得分:1)

你很接近,但仍有一些语法问题。

  • 列规范之间需要逗号。在KEY_INCOMEDATEKEY_INCOMETYPE之前的两个地方缺席。

  • 列规范中外键的语法只有REFERENCES,如KEY_ID + " INTEGER REFERENCES TABLE_User(uid)"

  • 或者,您可以使用FOREIGN KEY (column_name) REFERENCES other_table(other_column)语法在表约束中定义外键。表约束放在列规范之后。

示例:

private static final String CREATE_TABLE_income = "CREATE TABLE " + TABLE_income
    + "(" + KEY_IID + " INTEGER PRIMARY KEY," + KEY_AMOUNT + " TEXT," +KEY_ID + " INTEGER REFERENCES TABLE_user(uid)," 
    + KEY_INCOMEDATE + " DATETIME," +KEY_INCOMETYPE + " TEXT" + ")";

对于替代方法,请参阅Szymon的答案。

要强制执行外键约束,请记住设置例如PRAGMA foreign_keys = 'on'