如何在MySQL脚本中将列值分配给变量?

时间:2018-11-20 05:41:41

标签: mysql

我有以下脚本,但它始终返回null。

    SELECT 
    @PRICE_LARGE_PRICE = PRICE_LARGE_PRICE,
    @PRICE_SMALL_PRICE = PRICE_SMALL_PRICE
FROM
    prices
WHERE
    PRICE_LISTING_ID = 60;

SET @ITEM_PRICE = (CASE Size WHEN GivenLargeSizeName THEN @PRICE_LARGE_PRICE 
WHEN GivenSmallSizeName THEN @PRICE_SMALL_PRICE 
ELSE null 
END); 

这里的问题是

@PRICE_LARGE_PRICE = PRICE_LARGE_PRICE,
@PRICE_SMALL_PRICE = PRICE_SMALL_PRICE

表正确返回PRICE_LARGE_PRICE和PRICE_SMALL_PRICE,但分配不起作用。因此,CASE失败。

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

您需要使用SELECT ... INTO

SELECT PRICE_LARGE_PRICE, PRICE_SMALL_PRICE
INTO @PRICE_LARGE_PRICE, @PRICE_SMALL_PRICE
FROM prices
WHERE PRICE_LISTING_ID = 60;

请注意,您需要确保查询仅返回一行数据,并在必要时使用LIMIT 1

答案 1 :(得分:0)

SELECT 
    @PRICE_LARGE_PRICE:=PRICE_LARGE_PRICE,
    @PRICE_SMALL_PRICE:=PRICE_SMALL_PRICE
FROM
    prices
WHERE
    PRICE_LISTING_ID = 60;

只需在mysql中等号之前添加冒号