如何从表名是变量的 MySQL 中选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8809943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 22:18:49  来源:igfitidea点击:

How to select from MySQL where Table name is Variable

mysqlsettablename

提问by Burimi

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 会输出错误,所以有人可以告诉我如何实现这一点,因为这些是我在 MySQL 中的小步骤。

回答by Joe Stefanelli

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; 

回答by Palak Mantry

I got this solution after hours of debugging

经过数小时的调试,我得到了这个解决方案

The image i have attatched works 100% for mysql

我附上的图像 100% 适用于 mysql