SQL – Referential integrity

referential-integritysqlite

seems like my problem pretty much describes GC (Garbage Collector) but I don't want to make a procedure to run every X time. so this is my question:
I have three tables or more, refer to those as A,B,C.
C holds some columns and A & B refer to those columns.
A & B data can be deleted -> and here comes my question:
I'd like the referential to go as when there are no valid references to C, the referenced row will get deleted, since it's not in use.
I thought of adding an auto_increment to C, and make A & B refer to the index, and just keep multiple of the same data, and just delete the attached. This hardly seems like the most reasonable solution.
If anyone could point some light on my problem, that would be great.
Thank you.

EDIT: I'm using SQLite.

Best Answer

I would implement it using a reference counter:

CREATE TRIGGER new_in_b AFTER INSERT ON B
FOR EACH ROW 
BEGIN
  UPDATE A SET refcounter = refcounter + 1 WHERE id = new.foreignkey;
END;

CREATE TRIGGER remove_from_b AFTER DELETE ON B
FOR EACH ROW 
BEGIN
  UPDATE A SET refcounter = refcounter - 1 WHERE id = old.foreignkey;
  DELETE FROM A WHERE id = old.foreignkey AND refcounter = 0;
END;