42

我需要在我的 Android 应用程序中将数据从一个表移动到另一个表

我想使用以下sql:

insert into MYTABLE2 select id, STATUS risposta, DATETIME('now') data_ins from  MYTABLE 2

不幸的是,在表 MYTABLE2 中有一个 _ID 列 AUTOINCREMENT。我能做什么?

谢谢。

编辑: 这是我的 MYTABLE2,我想用另一个表中的数据填充该表:

CREATE TABLE "ANSWERS" ("_id" INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL ,
"ID_QUESTION" INTEGER,"DATE_INS" DATETIME DEFAULT 
(CURRENT_DATE) , "ANSWER" INTEGER)
4

3 回答 3

76

INSERT在子句中明确指定列名,

INSERT INTO destinationTable (risposta, data_ins)
SELECT STATUS risposta, DATETIME('now') data_ins 
FROM   sourceTable
于 2013-05-30T14:32:29.190 回答
5

这可能会有所帮助,从一个表到另一个表的查询,它还将检查所选列(id)是否已存在于另一个表中。

SQLite 查询:

INSERT INTO MYTABLE2(id,data_ins ) 
SELECT id, data_ins FROM MYTABLE2
WHERE id NOT IN ( SELECT id FROM MYTABLE1)

安卓:

 String select_insert_query = "INSERT INTO " + TABLE_MYTABLE2
            + "( " + ID + "," + DATA_INS + ") SELECT "
            + ID + ","
            + DATA_INS + " FROM "
            + TABLE_MYTABLE2
            + " WHERE " + ID + " NOT IN (SELECT " + ID
            + " FROM " + TABLE_MYTABLE1 + ")";

    SQLiteDatabase db = this.getWritableDatabase();

    Cursor cursor = db.rawQuery(select_insert_query, null);
    cursor.close();
于 2017-12-13T12:08:03.243 回答
4

您可以指定要插入的列。假设该_id列是autoincrement并且您正在插入另外两列,您可以有这样的东西:

insert into MYTABLE2 (riposta, data_ins)
select STATUS risposta, DATETIME('now') data_ins from  MYTABLE 2
于 2013-05-30T14:33:59.373 回答