0

我有下表和查询:

CREATE  TABLE IF NOT EXISTS `sizes` (
  `id_size` INT NOT NULL ,
  `cm_min` INT NOT NULL ,
  `cm_max` INT NOT NULL ,
  PRIMARY KEY (`id_size`) )
ENGINE = InnoDB;

insert into sizes values
(1,          56,        59),
(2,          63,        67),
(3,          70,        74),
(4,          76,        79),
(5,          83,        86),
(6,          60,        62),
(7,          12,        14);

  SELECT * FROM sizes
  WHERE cm_min >= 13 AND cm_min <= 66 OR
  cm_max >= 13 AND cm_max <= 66
  AND cm_min =
    (SELECT min(cm_max) FROM sizes
    WHERE (cm_min >= 13 AND cm_min <= 66) OR
    (cm_max >= 13 AND cm_max <= 66))
UNION
  SELECT * FROM sizes
  WHERE cm_min >= 13 AND cm_min <= 66 OR
  cm_max >= 13 AND cm_max <= 66
  AND cm_min =
    (SELECT min(cm_min) FROM sizes
    WHERE (cm_min >= 13 AND cm_min <= 66) OR
    (cm_max >= 13 AND cm_max <= 66))
ORDER BY cm_max ASC;

在 SqlFiddle 中查看


如您所见,这是一个值为 12 和 66 的示例。我需要在此查询中添加以下两个条件:

  1. 如果引入值的范围是所有表中最小的,则查询只返回具有最小值的行的数据。例如:如果我有值 9 和 10,结果将是 id_size 7,因为它是数字较小的那个。

  2. 如果引入值的范围是所有表中最大的,则查询只返回具有最大值的行的数据。例如:如果我有值 112 和 113,结果将是 id_size 5,因为它是具有较大数字的那个。


您知道如何将上述条件添加到我的查询中吗?我可以简化它吗?

4

1 回答 1

1

这应该可以解决问题。请注意,顺序很重要,@v1 必须是范围最小值,@v2 必须是最大值。

SET @v1=112, @v2=113;

SELECT *
FROM   sizes
WHERE  (
       cm_min BETWEEN @v1 and @v2
       AND
       cm_max BETWEEN @v1 and @v2
       )
OR
       cm_min = (
         SELECT MIN(cm_min)
         FROM   sizes
         WHERE  (@v1+@v2) <= (cm_min + cm_max)
         )
UNION
SELECT *
FROM   sizes
WHERE  (
       cm_min BETWEEN @v1 and @v2
       OR
       cm_max BETWEEN @v1 and @v2
        )
OR
       cm_max = (
         SELECT MAX(cm_max)
         FROM   sizes
         WHERE  (@v1+@v2) >= (cm_min + cm_max)
         )
ORDER BY cm_max ASC;
;
于 2013-02-15T12:22:28.467 回答