How do I use a column value as the database name to JOIN
two tables from those two different databases?
I have already successfully joined two tables between two databases with a statically defined (second) database name:
SELECT *
FROM db1.table_a AS ta
INNER JOIN db2.table_b AS tb on (ta.db_table_name = b.user_id)
However where db2.table_b
is in that query I need to somehow have the db2
instead be a value from the first table in the first database; the table name will be statically defined. All of the kind-of-related threads were totally useless and wildly convoluted.
Details: there is one common database and all of the other databases represent the same application but for different accounts. In order for all of the users on all of the different accounts to be able to interact with each other (e.g. database_2.accounts.user.43 (DB->Table->Column->ID (43)) the common database (db1
above) must not only store the id of the user but also the name of the database that must be joined.
To help visualize things:
- Database: common
- Database: db2
SELECT id, database_name
FROM common.table_a AS ct
INNER JOIN [database_name].table_b AS dn ON (ct.user_id = [database_name].users.id)
Visually the data returned should look something like this:
+----------+------------+----------+
| database | account_id | username |
+----------+------------+----------+
| db1 | 1 | John |
+----------+------------+----------+
| db2 | 1 | Sally |
+----------+------------+----------+
| db3 | 43 | John |
+----------+------------+----------+
| db4 | 1 | Sally |
+----------+------------+----------+
Then the HTML output should look something like this:
- Comment from John from db1.
- Comment from Sally from db2.
- Comment from John from db3.
- Comment from Sally from db4.
I can worry about ensuring visually that John from db1 and John from db3 (and Sally from db2 and Sally from db4) all four of which are different people in real life are represented as so. It's the dynamic aspect of selecting them based on the value of the column's value that contains the database name to be used to JOIN is all that matters.