title: SQL: How can we make a table1 JOIN table2 ON a table given in a field in table1?
body: <p>Imagine I have <code>table1</code> which has a column named 'table_name'. I use <code>table1</code>.table_name to store the name of another table in the database. The referenceable tables would all have a field 'target_id.</p>
  
  <p>Is is possible to use table_name in a JOIN statement?</p>
  
  <p>For example:</p>
  
  <pre><code>SELECT t1.*, t2.* FROM table1 AS t1
                    JOIN table1.table_name AS t2 ON t1.table1_id = t2.target_id
  </code></pre>
  
  <p>The obvious solution is to use the script (C++ in my case) to get the table name first, and construct a SQL query from it. The question is: can we bypass the script and do this directly in SQL (MySQL)?</p>
  
  <p>Edit: <a href="https://stackoverflow.com/questions/4165020">What is dynamic SQL?</a></p>