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

时间:2021-10-17 12:33:14

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中的小步骤。

1 个解决方案

#1


64  

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; 

#1


64  

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;