2013-05-15 199 views
0

您好我有一个表与下面的结构:如何选择超出范围的值?

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)); 

好了,知道我在想实现这个条件:

  • 如果范围比最高马克西更高表格,那么它会 选择最高最大元素的ID。
  • 如果范围低于表格的最小迷你部分,那么它会选择具有最小迷你部分的元素的编号为 的编号。

有可能做到这一点,而不使用更多的一个查询? 任何意见或建议,将不胜感激。

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

回答

1

一种方法是计算小的最小值和最大值马克西然后用这些作比较:

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) 
    ) 
+0

如果你想完成解决方案,我会改变你的方法成为一个联盟,如果OP想要所有的元素,或者他想要的是最低的和最高。 – RandomUs1r

+0

感谢作品完美! :) – harrison4