如何检查MySQL的任何价格范围内是否包含价格范围?

时间:2012-02-14 16:44:18

标签: mysql sql range

我想在表格中插入一个新的价格范围,但在我需要检查我的价格范围是否已包含在内或是否属于任何其他价格范围之前。

以下是一个例子:

我的价格范围表:

| minimum | maximum |
---------------------
|       1 |     100 |
|     201 |     300 |
|     301 |     400 |
  • 如果我提交[50,200],我必须拒绝它,因为50包含在[1,100]范围内。
  • 如果我提交[175,201],我必须拒绝它,因为201包含在[201,300]范围内。
  • 如果我提交[350,380],我必须拒绝,因为350和380属于[301,400]范围。
  • 如果我提交[120,190],我必须接受,因为120和190不包含在任何范围内。

我的问题是如果在我的表格中包含或不包括提交的范围,如何检查MySQL。

4 个答案:

答案 0 :(得分:1)

这应该有效(假设表名为ranges,新范围参数分别为@low和@high):

IF(NOT EXISTS (SELECT *
                 FROM ranges
                WHERE @low BETWEEN minimum AND maximum)
   AND 
   NOT EXISTS (SELECT *
                 FROM ranges
                WHERE @high BETWEEN minimum AND maximum))
BEGIN
     INSERT INTO ranges
         (minumum, maximum)
       VALUES
         (@low, @high)
END

当然,这可以进一步合并/缩小:

IF(NOT EXISTS (SELECT *
                 FROM ranges
                WHERE @low BETWEEN minimum AND maximum
                   OR @high BETWEEN minimum AND maximum))
BEGIN
     INSERT INTO ranges
         (minumum, maximum)
       VALUES
         (@low, @high)
END

更进一步:

INSERT INTO ranges
   (minimum, maximum)
SELECT T.minimum, T.maximum
  FROM (SELECT @low as minimum, @high as maximum) T
 WHERE NOT EXISTS (SELECT *
                     FROM ranges
                    WHERE @low BETWEEN minimum AND maximum
                       OR @high BETWEEN minimum AND maximum)

答案 1 :(得分:1)

INSERT INTO priceranges 
  SELECT * FROM 
    (SELECT <newminprice>, <newmaxprice>) AS baseview 
  WHERE NOT EXISTS (
    SELECT * FROM ranges 
    WHERE <newminprice> BETWEEN minimum AND maximum
      OR <newmaxprice> BETWEEN minimum AND maximum
  )

应该在一个查询中执行

答案 2 :(得分:0)

假设您要测试的新值为rangestart, rangeend,请在minimum AND maximum之间选择一个开头或结尾的行。任何结果行都将指示范围重叠且无法添加。如果此查询未返回任何行,则该范围不会重叠且有效。

SELECT 
  TRUE
FROM ranges
WHERE
   rangestart BETWEEN minimum AND maximum
   OR rangeend BETWEEN minimum AND maximum

答案 3 :(得分:0)

试试这个:

SELECT 'True' as Result
  FROM PriceRange
 WHERE iStartValue BETWEEN minimum AND maximum OR
       iEndValue   BETWEEN minimum AND maximum