【问题标题】:How to select values that are out of range?如何选择超出范围的值?
【发布时间】:2013-05-10 11:26:03
【问题描述】:

您好,我有一张表格,其结构如下:

create table prices(
    id int not null,
    mini float not null,
    maxi float not null,

    primary key (id)
);

然后我选择特定范围内的行的 ID。 以下小提琴不言自明:http://sqlfiddle.com/#!2/5885d/2

set @pmini1 = 82.5;
set @pmaxi1 = 85.5;

select *
from prices
where ((@pmini1 between mini and maxi) or 
(@pmaxi1 between mini and maxi));

好的,所以知道我试图实现这个条件:

  • 如果范围高于表格的最大最大值,那么它会 选择具有最高 maxi 的元素的 id。
  • 如果范围低于表的最低mini,那么它会选择id mini 最小的元素。

是否可以在不使用多个查询的情况下做到这一点? 任何建议或提示将不胜感激。

如果您需要更多信息,请告诉我,我会编辑帖子。

【问题讨论】:

    标签: mysql sql select


    【解决方案1】:

    一种方法是计算 mini 的最小值和 maxi 的最大值,然后使用它们进行比较:

    select *
    from prices p cross join
         (select MIN(mini) as minmini, MAX(maxi) as maxmaxi from p) const
    where ((@pmini1 between p.mini and p.maxi) or 
           (@pmaxi1 between p.mini and p.maxi) or
           (@pmini1 < const.minmini and p.mini = const.minmini) or
           (@pmaxi1 > const.maxmaxi and p.maxi = const.maxmaxi)
          )
    

    在 MySQL 中,您还可以更简洁地表述为:

    select *
    from prices p cross join
         (select MIN(mini) as minmini, MAX(maxi) as maxmaxi from p) const
    where ((greatest(@pmini1, const.minmini) between p.mini and p.maxi) or 
           (least(@pmaxi1, const.maxmaxi) between p.mini and p.maxi)
          )
    

    【讨论】:

    • 您在交叉连接的方法中 100% 正确,如果您想完成解决方案,我会将您的方法更改为联合,根据 OP 是否需要所有元素,可能会使用前 1,或者如果他只想要一个最低和最高的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-26
    • 1970-01-01
    相关资源
    最近更新 更多