我想在表格中插入一个新的价格范围,但在我需要检查我的价格范围是否已包含在内或是否属于任何其他价格范围之前。
以下是一个例子:
我的价格范围表:
| minimum | maximum |
---------------------
| 1 | 100 |
| 201 | 300 |
| 301 | 400 |
我的问题是如果在我的表格中包含或不包括提交的范围,如何检查MySQL。
答案 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