Delete entries from releted tables
I have got 2 tables: Contacts
and Users
.
Contacts
table contains user_id
which are referring to id
in Users
table. Contacts
also contain list_type
column.
Contacts: user_id, list_type
开发者_高级运维Users: id, data
How can I delete entries/rows from both tables (Contacts
and Users
) that are referring to given list_type
?
The trick is that i don't want to delete users
who belongs to other contacts list_type
.
EDIT:
Example:
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
Now I would like to delete list_type = 2, the result should be:
Users (id,data)
1 John - still is here, because it was also referring to list_type = 1
3 Alan
Contacts (user_id, list_type)
1 1
3 1
Break it down into two steps;
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"});
from what i understood, i can give you this answer.. i guess users table has user_id field.. I gave this roughly, you make it comfortable to your code.. :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;
EDIT:
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;
I would be tempted to do it with SQL. Let the database manage and clean itself, I say. Less back-and-forth between the database and your application, faster execution, and less code to maintain.
After any deletion from Contacts, run the following query:
DELETE FROM Users WHERE Id NOT IN (SELECT DISTINCT User_id FROM Contacts);
Or you could create a trigger and add it to your schema (which is even more hands-free!):
CREATE TRIGGER CleanUsers AFTER DELETE ON Contacts
BEGIN
DELETE FROM Users WHERE Id NOT IN (SELECT DISTINCT User_id FROM Contacts);
END;
精彩评论