PHP MySQL根据多列的范围进行选择

时间:2013-01-27 19:54:36

标签: php mysql select range

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

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切断它。

谢谢!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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
)";