In your case, you should set user_id as the primary key in user and as a foreign key in address . Thus, if you delete one of your users in user , you can set the ON DELETE CASCADE parameter to automatically delete related lines in the address.
When creating the table, you only need to do something like this:
CREATE TABLE user ( user_id INTEGER, user_name VARCHAR(30), PRIMARY KEY (user_id) ); CREATE TABLE address ( user_id INTEGER, address VARCHAR(30), PRIMARY KEY (user_id, address), FOREIGN KEY (user_id) REFERENCES user(user_id) ON DELETE CASCADE );
Basically, each user has a unique user_id . If you delete one of these users, the corresponding addresses in address will also be deleted, because the user.user_id address.user_id element "points to" has been deleted.
If you want to remove only those unused addresses, your solution should work fine.
source share