title: PostgreSQL link and unlink rows in chain manner
body: <p>A Document can be called family member if they share any common docid.</p>
  
  <p>Simple Mapping looks like:</p>
  
  <pre><code>Docs: docid
  1 : a,b
  2 : a,c,d
  3 : d,e,f
  4 : b,g
  </code></pre>
  
  <p>in table this data looks like :</p>
  
  <pre><code>1 = a
  1 = b
  2 = a
  2 = c
  2 = d
  3 = d
  3 = e
  3 = f
  4 = b
  4 = g
  </code></pre>
  
  <p>Here 1,2,3,4 Documents are family as they have commons like : 1 and 2 share "a" as common, 2 and 3 share "d" as common and 1 and 4 share "b" as common. </p>
  
  <p>I can achieve this grouping by making a separate table of it and while inserting checking if any record exists then assigning existing value to all the docid.</p>
  
  <pre><code>When doc 1 is inserted :
  checks any of (a,b) already in family table:
  if no:
    insert into table and get a famid
  </code></pre>
  
  <p>hence inserts : a = 1 and b=1 rows.</p>
  
  <p>and for other cases
  eg doc 2 case</p>
  
  <pre><code>: any (a,c,d) exists --&gt; doc 1 has been inserted hence output : a = 1
  
  so take this value and assign to a,c,d (separate entries: a=1, c=1, d=1)and upsert into family table. 
  </code></pre>
  
  <p>So the family table looks like:</p>
  
  <pre><code>Docs : docid : famid
  1    :   a   :  1
  1    :   b   :  1
  2    :   c   :  1
  2    :   d   :  1
  3    :   e   :  1
  3    :   f   :  1
  4    :   g   :  1
  </code></pre>
  
  <p><strong>I want to keep this as to maintain group by so that in this case if I have doc 1,2,3,4 i can group by famid and return any one of these 4 docs.</strong></p>
  
  <p><strong>My concern</strong> is these docid may contain manual error hence after few days "a" might get unlink from doc1 so logically docs 2 and 3 should not be member of family famid 1 anymore but the family table still stores it hence complete chain gets corrupted is there a way I can store and maintain so as to unlink in case of deletion of a common node in chain.</p>