0

我有一个类似于以下的表格设置:

CREATE table TABLE_prices
(
PRICE_ID int unsigned not null auto_increment primary key,
RANGE1_START int,
RANGE1_END int,
RANGE1_PRICE decimal(10,2),
RANGE2_START int,
RANGE2_END int,
RANGE2_PRICE decimal(10,2),    
RANGE3_START int,
RANGE3_END int,
RANGE3_PRICE decimal(10,2)
);

如果我有一个值(例如 100),有没有办法构建一个 select 语句来根据值所在的范围获取 RANGE#_PRICE?

我的直觉是,我可能不得不从 MySQL 中提取范围数据并在 PHP 中对其进行迭代,但我不知道是否有办法使用 MySQL 直接切入它。

谢谢!

4

2 回答 2

0

试试这个丑陋的解决方案:

SELECT
  PRICE_ID,
  COALESCE(
            CASE WHEN @value BETWEEN RANGE1_START AND RANGE1_END THEN RANGE1_PRICE END,
            CASE WHEN @value BETWEEN RANGE2_START AND RANGE2_END THEN RANGE2_PRICE END,
            CASE WHEN @value BETWEEN RANGE3_START AND RANGE3_END THEN RANGE3_PRICE END
          ) Price
FROM TABLE_prices
于 2013-01-27T19:59:49.790 回答
0

我不知道您要实现什么目标,但您可以在单个语句中做到这一点:

$price = 100;

$sql = "
(
  SELECT 1 as range, price_id, range1_start as range_start, range1_end as range_end FROM table_prices WHERE range1_start >= $price AND range1_end <= $price
) UNION
(
  SELECT 2 as range, price_id, range2_start as range_start, range2_end as range_end FROM table_prices WHERE range2_start >= $price AND range2_end <= $price
) UNION
(
  SELECT 3 as range, price_id, range3_start as range_start, range3_end as range_end FROM table_prices WHERE range3_start >= $price AND range3_end <= $price
)";
于 2013-01-27T20:02:12.690 回答