How to select from MySQL where Table name is Variable

MysqlSetTablename

Mysql Problem Overview


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.

Mysql Solutions


Solution 1 - Mysql

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; 

Solution 2 - Mysql

I got this solution after hours of debugging

The image i have attatched works 100% for mysql

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRosmarine PopcornView Question on Stackoverflow
Solution 1 - MysqlJoe StefanelliView Answer on Stackoverflow
Solution 2 - MysqlPalak MantryView Answer on Stackoverflow