Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As this is a many-to-many relation, you migth might want to have a look at using an associative table.</p> <p>Using your example, it might look something like this:</p> <p>Your tables that can <strong>have</strong> comments:</p> <pre><code>+----------+------------+ | student | student_id | +----------+------------+ | Steve | 12 | | Larry | 57 | | Sunshine | 88 | +----------+------------+ +--------+---------+ | dept | dept_id | +--------+---------+ | Math | 2 | | P.E. | 5 | | Drama | 12 | +--------+---------+ </code></pre> <p>Then you need to keep track of the actual comments:</p> <pre><code>+-----------------------+------------+ | comment | comment_id | +-----------------------+------------+ | I love Math! | 3 | | Larry is my hero... | 5 | | Sunshine &lt;3 Me! | 6 | +-----------------------+------------+ </code></pre> <p>Now, you need an association between these tables, this is where your associative table comes into play. You now associate what student or dept has what comments, like this:</p> <pre><code>+------------+------------+ | student_id | comment_id | +------------+------------+ | 57 | 5 | | 57 | 6 | +------------+------------+ +---------+------------+ | dept_id | comment_id | +---------+------------+ | 2 | 3 | +---------+------------+ </code></pre> <p>This is both effective and elegant. Give it a shot!</p> <p><em>(And to save you another question perhaps)</em></p> <p>You could of course use just one association table if you are concerned about having so many association tables, but I would advice against it since it is not as neat and removes some possibilities for referential integrity checks that you can have with the first solution:</p> <pre><code>+-----------+------------+---------+ | entity_id | comment_id | entity | +-----------+------------+---------+ | 57 | 5 | student | | 57 | 6 | student | | 2 | 3 | dept | +-----------+------------+---------+ </code></pre> <p>(Which in turn should prompt you to add a lookup table for those entities... but let's not go there)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload