如何根据mysql中的另一列选择列?

arknldoa  于 2021-06-19  发布在  Mysql
关注(0)|答案(2)|浏览(395)

下面的脚本运行良好。但我想写一行而不是三行大小“是通过我的主程序和它在这里用来测试。我只是想根据尺寸来定价。
表列:listing\u id、price\u large\u price、price\u small\u price。

SET @Size = 'SMALL';

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

SET @ITEM_PRICE = (CASE @Size WHEN 'REGULAR' THEN @PRICE_LARGE_PRICE 
WHEN 'SMALL' THEN @PRICE_SMALL_PRICE 
ELSE null 
END); 

SELECT @ITEM_PRICE;

感谢您的帮助。

s1ag04yj

s1ag04yj1#

我想你想要

SELECT 
  IF(@size == 'SMALL', PRICE_SMALL_PRICE, PRICE_LARGE_PRICE) AS ITEM_PRICE 
FROM prices;
ix0qys7i

ix0qys7i2#

以下步骤可能有效。

SET @Size = 'SMALL';

SELECT 
    PRICE_LARGE_PRICE,
    PRICE_SMALL_PRICE, 
    CASE WHEN @Size = 'REGULAR' THEN PRICE_LARGE_PRICE
         WHEN @Size = 'SMALL' THEN PRICE_SMALL_PRICE
    END AS ITEM_PRICE 
INTO
    @PRICE_LARGE_PRICE,
    @PRICE_SMALL_PRICE, 
    @ITEM_PRICE 
FROM
    prices
WHERE
    PRICE_LISTING_ID = 60;

相关问题