删除表中的重复内容

时间:2012-07-20 13:47:33

标签: sqlite

我有一个包含这些字段的表table_news

_ID = INTEGER PRIMARY KEY AUTOINCREMENT 
ID = TEXT NOT NULL 
CONTENT = TEXT NOT NULL
ZONE TEXT = NOT NULL 
AREA TEXT = NOT NULL
TITLE TEXT = NOT NULL
DATE TEXT = NOT NULL
AUTHOR TEXT = NOT NULL

此表填写如下:

Column    Row 1 Value                   Row 2 Value
------------------------------------------------------
_ID       1                             2
ID        "5"                           "5"
CONTENT   "Discover New York."          "Discover New York."
ZONE      "New York"                    "New York"
AREA      "New York"                    "New York"
TITLE     "Let's discover the world."   "Let's discover the world."
DATE      "2012-07-04"                  "2012-07-04"   
AUTHOR    "Henry Brakman"               "Henry Brakman"

所以我只想创建一个SQL语句来删除其中一个重复的行。

我试过这个(添加换行符以便于阅读,命令写成单个字符串):

public SQLiteStatement removeSameContentNews() { 
   return bdd.compileStatement("DELETE FROM table_news "
      + "WHERE _ID NOT IN (SELECT MIN( _ID) "
      + "FROM table_news "
      + "GROUP BY ID, CONTENT, ZONE, AREA, TITLE, DATE, AUTHOR)"); 
}

但这没有删除任何内容..

我最终使用UNIQUE关键字的唯一性并且它正常工作:

private static final String CREATE_TABLE_NEWS = 
   "CREATE TABLE " + TABLE_NEWS + " (" + COLUMN_ROWID 
   + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_ID 
   + " TEXT NOT NULL UNIQUE, " + COL_CONTENT 
   + " TEXT NOT NULL, " + COL_ZONE + " TEXT NOT NULL, "
   + COL_AREA + " TEXT NOT NULL, " + COL_TITLE 
   + " TEXT NOT NULL, " + COL_DATE + " TEXT NOT NULL, " 
   + COL_AUTHOR + " TEXT NOT NULL);";

1 个答案:

答案 0 :(得分:2)

您可以使用此查询示例:

DELETE FROM table WHERE _ID NOT IN (
    SELECT MIN( _ID) 
    FROM table 
    GROUP BY ID, CONTENT, ZONE, AREA, TITLE, DATE, AUTHOR
)

修改

或者你可以使用:

DELETE FROM table_news WHERE EXISTS
  (SELECT 1 FROM table_news t
    WHERE t.ID=table_news.ID AND 
    t.ID=table_news.CONTENT AND  
    t.ID=table_news.ZONE AND  
    t.ID=table_news.AREA AND  
    t.ID=table_news.TITLE AND  
    t.ID=table_news.DATE AND  
    t.ID=table_news.AUTHOR AND 
    t.rowid > table_news.rowid)