Reputation: 75
Not sure if it's possible via a query but bear with me.
Let's say I have the following table:(Let's call it: 'tables')
id | table
---------
1 | Table1
2 | Table2
3 | Table3
I'd like to create a query that selects data from the dynamic table name inside a row.
Something like:
select * from (select table from tables where id = 1)
Expected resulted from this query is all rows and columns from "Table1".
Is something like this can be done via MySQL?
I couldn't find any information about this so anything will probably help.
Upvotes: 1
Views: 48
Reputation: 282
Probably you cant do this with one query, and you need a server side language to get this done in two steps,
first get the table's name by running this query
select table from tables where id = 1
then save the result in a vaiable , lets assume it is on PHP, $tab
now you can run your main query by integrating the $tab
variable which contain the name of the table you look for, this will give a clear MySQL query to execute
select * from $tab
Upvotes: 0
Reputation: 39981
You can create a prepared statement, possibly inside a stored procedure to accomplish this.
Also, as @strawberry says in a comment, this is a sign of bad design. Even if it's possible to solve you should probably rethink your design.
Upvotes: 2