MySql - using dynamic table names in one query -


i have following tables:

cars

  • id
  • name
  • color

bicycles

  • id
  • name
  • number_of_gearshift

i need central index table of tables in mysql database , unique id them. this:

items

  • id
  • table_name

lets say, id in items-table same in corresponding table:

items

id | table_name  1 | cars  2 | cars  3 | bicycles  4 | cars 

cars

id | name        | color  1 | peugeot     | red  2 | bmw         | green    4 | nissan      | blue 

bicycles

id | name      | number_of_gearshift  3 | stevens   | 24 

my question - following situation: have id (for example xxx) of item. want data of item, 1 query. (i know, not work):

select table2.* (select table_name items id = xxx) table2 

is possible?

use can use dynamic sql query achieve this.

set @query = null; set @id = 3;/*change according requirement*/ set @tn := (select `table_name` items id =  @id);  set @query = concat('select * ',@tn,' id = ',@id);  prepare stmt @query; execute stmt; deallocate prepare stmt; 

change value of @id according requirement.

sql fiddle


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -