我有两张桌子:Contacts
和Users
。
Contacts
表包含user_id
,表示id
表中的Users
。 Contacts
还包含list_type
列。
Contacts: user_id, list_type
Users: id, data
如何从两个表(Contacts
和Users
)中删除引用给定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
答案 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;