mysql - How can I join a database and table where the database name is derived from a field in the current table? -


i have database server stores main database and, table within database has structure similar below

companies.companyinfo

id | name     | databasename | otherinfo ---+----------+--------------+---------- 0  | companya | databasea    | extra1 1  | companyb | databaseb    | extra2 

and company databases follows

databasea.users

userid | name    | password  |  -------+---------+-----------+--------- 0      | user1   | pass1     | other1 1      | user2   | pass2     | other2 

and databaseb similar.

what want user information 1 of usertable, linked main database

so want kind of subselect user details, feed database name subselect companies.companyinfo table query.

i'm stuck.. please help!

it's not entirely clear you're after, in principle 1 cannot use expressions (including value of field table lookup) identifiers (e.g. name of table or column).

one workaround 'prepare' statement string containing desired query; such string can constructed concatenating expressions in place of identifiers:

select concat(   'select * `', replace(databasename, '`', '``'), '`.users' ) @qry companies.companyinfo id = 1;  prepare stmt @qry; execute stmt; 

however, may easy obtain database name in application using 1 select query, , perform same concatenation issue second query there.

all of said, perhaps data structure needs further normalisation? why not combine of databases one, column in each table indicating company each record relates?


Comments

Popular posts from this blog

django - How can I change user group without delete record -

java - Need to add SOAP security token -

java - EclipseLink JPA Object is not a known entity type -