如何从表名为变量的 MySQL 中进行选择

2022-01-17 00:00:00 set mysql tablename

我有一种情况,应该从一个集合变量中获取表名,例如:

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

但是这样做 MySQL 会输出错误,所以有人可以告诉我如何实现这一点,因为这些是我在 MySQL 中的初级步骤.

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.

推荐答案

你必须使用 准备好的语句.比如:

SET @s = CONCAT('select * from ', @Cat, ' where ID = ', @ID_1); 

PREPARE stmt1 FROM @s; 
EXECUTE stmt1; 
DEALLOCATE PREPARE stmt1; 

相关文章