使用mySQL变量

Wil*_*ill 2 mysql variables

是否有可能在一系列SQL语句中获取字段的值并使用它来命名另一个语句中的表?我不确定这是否清楚,所以这是一个psudo - 我正在尝试做的例子:

// dataType is equal to "ratings"
@var = select dataType from theTable where anID = 5;

// needs to run as "from ratings-table"
select field1,field2 from @var-table where anID = 5;
Run Code Online (Sandbox Code Playgroud)

我一直在阅读http://dev.mysql.com/doc/refman/5.0/en/user-variables.html,但要么我没有正确理解这一点,要么它不是我正在寻找的解决方案.

Teh*_*ike 5

是的,您可以使用预准备语句执行此操作:

SET @TableName := 'ratings';
SET @CreateQuery := CONCAT('SELECT `field1`, `field2` FROM `', @TableName, '-table` WHERE `anID` = 5');
PREPARE statementCreate FROM @CreateQuery;
EXECUTE statementCreate;
Run Code Online (Sandbox Code Playgroud)