在SELECT(MySQL)程序中设置SET

时间:2018-03-02 21:56:01

标签: mysql sql

我想得到的是user_discount.percent内的DiscountVar

所以在THEN SET我可以返回一个值discount = DiscountVar

BEGIN
DECLARE DiscountVar FLOAT(28,10);

IF EXISTS 
(
SELECT
    user_discount.percent as DiscountVar,
    user_discount.link_id,
    user_discount.pacc_id,
    user_discount.timestamp_valid
FROM 
    user_discount
WHERE 
    user_discount.link_id = wo_id 
AND user_discount.pacc_id = pacc_id
AND UTC_TIMESTAMP>=user_discount.timestamp_valid
ORDER BY 
    user_discount.timestamp_valid DESC
LIMIT 1
)

THEN SET discount = DiscountVar;

ELSE SET discount = 0;
END IF;

END

这可能吗?

我已尝试过此user_discount.percent AS percent INTO @DiscountVar,但它没有效果......

它上面有IF EXISTS个作品。我只需要进行第二次选择,只需输出THEN中的数据。

1 个答案:

答案 0 :(得分:0)

查询中的别名不等同于过程变量。如果要分配给变量,请使用SELECT ... INTO

您还可以使用:=的作业。但我认为你必须使用带有@前缀的用户变量,而不是声明的变量。

当您使用EXISTS执行查询时,它只测试查询是否与任何行匹配,它不会执行分配。不要使用EXISTS,而是执行SELECT并检查变量是否已设置。

BEGIN

SELECT
    @DiscountVar := user_discount.percent,
    user_discount.link_id,
    user_discount.pacc_id,
    user_discount.timestamp_valid
FROM 
    user_discount
WHERE 
    user_discount.link_id = wo_id 
AND user_discount.pacc_id = pacc_id
AND UTC_TIMESTAMP>=user_discount.timestamp_valid
ORDER BY 
    user_discount.timestamp_valid DESC
LIMIT 1;

SET discount = IFNULL(@DiscountVar, 0);

END