title: Use a user-defined variable to dynamically name second database to JOIN tables with that second database
body: <p>I need to <code>JOIN</code> two different databases which I've already accomplished <em>statically</em> for testing purposes only.</p>
  <ol>
  <li>The first database is already defined in the connection itself.</li>
  <li>The second database must be dynamically derived from information within the first database that <em>must first be defined in a user-defined variable</em>. To keep things simple I will simply refer to the second database name as <code>example2</code>.</li>
  <li>Statically defining the second database name works and all the <code>JOIN</code>ed data is successfully pulled <em>however</em> with my current comprehension if I did this on a live (or &quot;production&quot;) server I'd have to run two separate queries on the same connection with some PHP code in between those two queries.</li>
  <li>I can not define the second database name without running a second query and the point is to avoid making multiple connections to the SQL server when I know there is a way to do it in a single query (if we do not count setting a user-defined variable a query).</li>
  </ol>
  <p>Here is a static demonstration of what worked for me:</p>
  <pre><code>SELECT * FROM example1 AS e1 
  INNER JOIN example2.accounts AS e2a ON (e2a.id = e1.accounts_id);
  </code></pre>
  <p>However the following does not work:</p>
  <pre><code>SET @db = 'example2';
  SELECT * FROM example1 AS e1 
  INNER JOIN @db.accounts AS e2a ON (e2a.id = e1.accounts_id);
  </code></pre>
  <p>How can I set and use a user-defined variable to <em>dynamically</em> define the second database's name and use it to dynamically <code>JOIN</code> the tables between the two databases?</p>
  <ul>
  <li>All data is properly stored/formatted/etc.</li>
  <li>I already have the user-defined variable working, I need help implementing it on the database-to-database JOIN.</li>
  <li>This sort of relates to the fact that PHP has <a href="https://stackoverflow.com/a/2715671/606371">variable variables</a>.</li>
  </ul>