如何基于mySQL中的另一列选择列?

时间:2018-11-21 15:30:37

标签: mysql select case case-when

以下脚本可以正常工作。但是我想写成一行而不是三行。 “尺寸”是从我的主程序传递过来的,并在这里用于测试。我只是想根据尺寸获得价格。

表格列: LISTING_ID,PRICE_LARGE_PRICE,PRICE_SMALL_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;

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

我想你想要

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

答案 1 :(得分:1)

以下可能有效。

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;