Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>No, you can't join to a different table per row in <code>table1</code>, not even with dynamic SQL as @Cade Roux suggests. </p> <p>You could join to the <code>hotdog</code> table for rows where food is 'hotdog' and join to other tables for other specific values of food.</p> <pre><code>SELECT * FROM table1 JOIN hotdog ON id = foodid WHERE food = 'hotdog' UNION SELECT * FROM table1 JOIN apples ON id = foodid WHERE food = 'apples' UNION SELECT * FROM table1 JOIN soups ON id = foodid WHERE food = 'soup' UNION ... </code></pre> <p>This requires that you know all the distinct values of food, and that all the respective food tables have compatible columns so you can UNION them together.</p> <p>What you're doing is called <em>polymorphic associations</em>. That is, the foreign key in <code>table1</code> references rows in multiple "parent" tables, depending on the value in another column of <code>table1</code>. This is a common design mistake of relational database programmers.</p> <p>For alternative solutions, see my answers to:</p> <ul> <li><a href="https://stackoverflow.com/questions/441001/possible-to-do-a-mysql-foreign-key-to-one-of-two-possible-tables/441111#441111">Possible to do a MySQL foreign key to one of two possible tables?</a></li> <li><a href="https://stackoverflow.com/questions/922184/why-can-you-not-have-a-foreign-key-in-a-polymorphic-association/922341#922341">Why can you not have a foreign key in a polymorphic association?</a></li> </ul> <p>I also cover solutions for polymorphic associations in my presentation <a href="http://www.slideshare.net/billkarwin/practical-object-oriented-models-in-sql" rel="nofollow noreferrer">Practical Object Oriented Models In SQL</a>, and in my book <a href="http://pragprog.com/book/bksqla/sql-antipatterns" rel="nofollow noreferrer">SQL Antipatterns: Avoiding the Pitfalls of Database Programming</a>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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