从相关表中删除条目

时间:2010-08-27 13:15:46

标签: sql android sqlite

我有两张桌子:ContactsUsers

Contacts表包含user_id,表示id表中的UsersContacts还包含list_type列。

Contacts: user_id, list_type Users: id, data

如何从两个表(ContactsUsers)中删除引用给定list_type的条目/行?

诀窍是我不想删除属于其他联系人users的{​​{1}}。

编辑:

示例:

list_type

现在我想删除list_type = 2,结果应为:

Users (id,data)
1    John
2    Kate
3    Alan
4    Bob

Contacts (user_id, list_type)
1    1
3    1
1    2
4    2
2    2

3 个答案:

答案 0 :(得分:2)

将其分解为两个步骤;

SQLiteDatabase db;
        Cursor c = db
                .query("Contacts", new String[] { "user_id" }, "list_type=?",
                        new String[] { "list_type_1" }, null, null, null);

        if(c.moveToFirst()){
            do{
                db.delete("Users", "user_id=?",new String[]{c.getString(c.getColumnIndex("user_id"))});
            }while(c.moveToNext()));
        }

        db.delete("Contacts", "list_type=?", new String[]{"list_type_1"});

答案 1 :(得分:1)

从我的理解,我可以给你这个答案..  我猜用户表有user_id字段..我粗略地给出了这个,你让你的代码感到舒服..:D

   select user_ids from contacts where list_type=some_type;

    while(resultSet.next()){
         String userid=restultSet.getString(1);
         delete from users where user_ids=userid;
    }
    delete from contacts where list_type=some_type;

编辑:

resultSet_1 = select user_ids from contacts where list_type=some_type;  

while(resultSet_1.next()){
   String userid=resultSet_1.getString(1);
   resultSet_2 = select count(user_ids) from contacts where user_id=userid group by user_ids;
   int count=resultSet_2.getInt(1);

   if(count==1){     //if more than 1 it means contact is in more than one list_type
       delete from users where user_ids=userid;
   }
}
delete from contacts where list_type=some_type;

答案 2 :(得分:1)

我很想用SQL做到这一点。我说,让数据库管理和清理自己。数据库和应用程序之间来回减少,执行速度更快,维护代码更少。

从“联系人”中删除任何内容后,请运行以下查询:

DELETE FROM Users WHERE Id NOT IN (SELECT DISTINCT User_id FROM Contacts);

或者您可以创建一个触发器并将其添加到您的架构中(这更加免提!):

CREATE TRIGGER CleanUsers AFTER DELETE ON Contacts 
  BEGIN
    DELETE FROM Users WHERE Id NOT IN (SELECT DISTINCT User_id FROM Contacts);
  END;