选择语句作为表名称中的MySQL用户定义变量

时间:2014-12-08 18:00:27

标签: mysql variables case

我可以使用前一个select语句中定义的用户定义变量作为另一个的表列吗?

示例:

SELECT `name`
INTO @_ptType
FROM `point_types`
WHERE `id` = _case;

SELECT SUM(@_ptType)
INTO _awardedPts
FROM `subscribers_points`
WHERE `subscriber_id` = _subscriber_id
GROUP BY `subscriber_id`;

SELECT `id`
INTO _badgeID
FROM `badges`
WHERE `trigger_point` = _awardedPts
AND `point_type_id` = _case;

让我们说出这个名字'在第一个选择中返回@_ptType是'特殊'

下一个选择应返回该列的值' special' sub_id等匹配,是吗?

我一直收到错误:"没有数据 - 获取,选择或处理零行#34;

提前致谢。

1 个答案:

答案 0 :(得分:1)

诀窍是使用动态SQL字符串创建预准备语句:

SET @sql_text = "SELECT SUM(@_ptType)
                 INTO _awardedPts
                 FROM `subscribers_points`
                 WHERE `subscriber_id` = _subscriber_id
                 GROUP BY `subscriber_id`;";

PREPARE stmt FROM @sql_text;

EXECUTE stmt;

DROP PREPARE stmt;