1

I have these tables:

items:

+ _id
+ timestamp

itemlists:

+ _id
+ timestamp

linktable:

+ _id
+ item_id foreign key references items(_id)
+ item_list_id foreign key references item_list(_id)

An item can be in many lists. A list can contain many items. It's a many-to-many relationship.

I now want to delete an itemlist and all items in it, if they are unique to that list. However I don't want to delete any item from items table if they are in another list as well.

I can retrieve all items for a specific playlist:

items a inner join item_list b on a._id = b.item_id where item_list_id = ?

But I'm struggling with how to structure a delete for a specific list and its items, without deleting items that are also referenced by another list that is not deleted.

Any pointers in the right direction are highly appreciated.

I'm running this on SQLite on Android.

2
  • if you want to delete an entire table can you not use dropTable? Commented Feb 5, 2015 at 7:29
  • Not an entire table. I want to delete a list from itemlists, and all items in items table if they are only in that list. If they are also in another list I can't delete them from the items table. Commented Feb 5, 2015 at 7:34

1 Answer 1

1

First, delete the list:

DELETE FROM itemlists WHERE _id = ?;

Then delete all its links:

DELETE FROM linktable WHERE item_list_id = ?;

Then delete all items that have no link left:

DELETE FROM items WHERE _id NOT IN (SELECT item_id FROM linktable);

Do all this in a single transaction.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.