title: Mysql : delete row automatically if there is no more references (among several) to it
body: <p>In my database, I have 2 tables : Messages, and Updates. These 2 tables store some informations like a text, AND can have 0, 1 or several parameters. To hold these parameters, I have 2 other tables : Messages_params and Updates_params. These 2 tables have the same columns :</p>
  <ul>
  <li>ID</li>
  <li>ID_message/ID_update</li>
  <li>key</li>
  <li>raw_value (can be null)</li>
  <li>ID_direct_reference (can be null)</li>
  </ul>
  <p>These parameters can be either : raw value (stored as varchars), in this case raw_value equals the actual value and ID_direct_reference is null OR an ID to what I call a &quot;direct reference&quot;. These direct references are just tables containing a PHP class name and that can have their own parameters.</p>
  <p>So I have 2 other tables holding these direct references and their parameters : direct_reference (ID, class_name) and direct_reference_params(ID, ID_direct_reference, key, value).</p>
  <p>Basically, I'm doing this system to have dynamic parameters for my app updates and messages. For example, let's say user A likes photo of user B. An update is created for user B that needs to say &quot;{pseudo of user A} likes your photo&quot;. Update is created immediatly, but delivered to the client app only when user B is on it and  polls for new updates. If user B returns to the app one hour after the update was created AND if user A changed its pseudo meanwhile, user B would receive the update with the old user A pseudo. So basically, I want to compute some update parameters <strong>at the moment they are delivered</strong> (and not at the moment they are created).</p>
  <p>When the update (or the message) is delivered, my server checks for direct references in its params; it calls a particular method of the Direct reference <code>classname</code> (via PHP reflection), and sends the direct reference parameters to this method, so the class knows what to return.</p>
  <p>Now comes my question : I want these direct references to be deleted when their holder is deleted, automatically, by foreign keys in mysql. But, as these direct references can be theorically held by several rows in several tables (messages params and updates params and whatever thing params that could need them), how can I say to mysql &quot;Delete automatically the direct reference row (and the associated DR params) if no row, in no table contains anymore ID of it&quot;.</p>
  <p>Thanks for having read this complicated question.</p>