Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select from MySQL where Table name is Variable

I have a case where getting the table name should be from a set variable like:

SET @ID_1 = (SELECT ID FROM `slider` LIMIT 0,1); SET @Cat = (SELECT Category FROM `slider` LIMIT 0,1); select * from @Cat where ID = @ID_1 

but doing that way MySQL outputs an error, so could someone show me how I can achieve that, because these are my baby steps in MySQL.

like image 324
Rosmarine Popcorn Avatar asked Jan 10 '12 20:01

Rosmarine Popcorn


People also ask

How do you reference a variable in MySQL?

User variables are written as @ var_name , where the variable name var_name consists of alphanumeric characters, . , _ , and $ . A user variable name can contain other characters if you quote it as a string or identifier (for example, @'my-var' , @"my-var" , or @`my-var` ).

How do I select a specific value from a table in MySQL?

MySQL SELECT statement is used to retrieve rows from one or more tables. The statement can also include UNION statements and subqueries. SELECT statement is used to fetch rows or records from one or more tables.

How do I find a specific data in MySQL?

MySQL WorkbenchThere is a Schemas tab on the side menu bar, click on the Schemas tab, then double click on a database to select the database you want to search. Then go to menu Database - Search Data, and enter the text you are searching for, click on Start Search.

How do I select a table in MySQL?

A SELECT statement begins with the SELECT keyword and is used to retrieve information from MySQL database tables. You must specify the table name to fetch data from—using the FROM keyword—and one or more columns that you want to retrieve from that table. A keyword is a word that is part of the SQL language.


1 Answers

You'd have to do this with a prepared statement. Something like:

SET @s = CONCAT('select * from ', @Cat, ' where ID = ', @ID_1);   PREPARE stmt1 FROM @s;  EXECUTE stmt1;  DEALLOCATE PREPARE stmt1;  
like image 180
Joe Stefanelli Avatar answered Sep 20 '22 15:09

Joe Stefanelli