如何在 sqlite 中使用复合主键创建 table?

How to create a table with composite primary key in sqlite?

我有一个 Android 应用程序,我只想创建一个带有 2 个主键的 table:

public static final String SCRIPT_CREATE =
        "CREATE TABLE IF NOT EXISTS " + TABLE_FOLDER_AUSCULTATION + "("
                + COL_FOLDER_ID + " INTEGER, "
                + COL_REMOTE_FOLDER_ID + " INTEGER PRIMARY KEY, "
                + COL_AUSCULTATION_ID + " INTEGER, "
                + COL_REMOTE_AUSCULTATION_ID + " INTEGER, "
                + COL_CREATE_AT + " INTEGER DEFAULT 0, "
                + COL_MODIFIED_AT + " INTEGER DEFAULT 0, "
                + COL_SYNC_STATUS + " text, "
                + "primary key (" + COL_REMOTE_FOLDER_ID + ", " + COL_REMOTE_AUSCULTATION_ID +")"
                + ");";

但我收到以下错误:

E/SQLiteLog: (1) table "folderAuscultation" has more than one primary key
I/MDEBUG: Error DBHelper.onCreate
android.database.sqlite.SQLiteException: table "folderAuscultation" has more than one primary 
key (code 1): , while compiling: CREATE TABLE IF NOT EXISTS folderAuscultation(folderId 
INTEGER, remoteFolderId INTEGER PRIMARY KEY, IdAuscultation INTEGER, remoteAuscultationId 
INTEGER, createdAt INTEGER DEFAULT 0, modifiedAt INTEGER DEFAULT 0, syncStatus text, primary 
key (remoteFolderId, remoteAuscultationId));
    at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
    at 
android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:890)
    at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:501)
    at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
    at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
    at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
    at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1753)
    at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1682)
    at br.com.conectivida.mdconnect.db.DBHelper.onCreate(DBHelper.java:71)
    at br.com.conectivida.mdconnect.db.DBHelper.createTablesIfNotExists(DBHelper.java:136)
    at br.com.conectivida.mdconnect.db.DBHelper.onUpgrade(DBHelper.java:132)

我的语法有误吗?创建此结构的正确方法是什么?

在您的 table 定义的前面,您将列 COL_REMOTE_FOLDER_ID 定义为主键。因此,当遇到第二个复合主键定义时,就会出现错误。删除第一个主键定义,它应该可以工作:

public static final String SCRIPT_CREATE =
    "CREATE TABLE IF NOT EXISTS " + TABLE_FOLDER_AUSCULTATION + "("
            + COL_FOLDER_ID + " INTEGER, "
            + COL_REMOTE_FOLDER_ID + " INTEGER, "
            + COL_AUSCULTATION_ID + " INTEGER, "
            + COL_REMOTE_AUSCULTATION_ID + " INTEGER, "
            + COL_CREATE_AT + " INTEGER DEFAULT 0, "
            + COL_MODIFIED_AT + " INTEGER DEFAULT 0, "
            + COL_SYNC_STATUS + " TEXT, "
            + "PRIMARY KEY (" + COL_REMOTE_FOLDER_ID + ", " + COL_REMOTE_AUSCULTATION_ID +")"
            + ");";