2017-06-27 57 views
1

我想查询一个表以首先找到匹配失败的列的完全匹配, ;选择范围内最接近的一个。在一次调用中合并两个Select语句

例如,

TestTable的

id  width  cost 

    1   10.2  100 
    2   10.5  200 
    3   10.1   50 

Select * from testTable where width = 10.3; 

的情况下,这将返回不记录我想在10.1的范围内去最近的一个至10.9。

EDIT1:它是Oracle;更新标签

+0

这是MySQL或Oracle数据库问题吗?请仔细标记。 – tadman

+0

如果多于一行是“最接近”的呢? “最近的**一个**”意味着它是独一无二的;但即使'width'列没有重复项,在你的例子中10.5和10.1同样“接近”到10.3。你想选择它们吗? – mathguy

+0

我删除了不兼容的数据库标签。请仅使用您正在使用的数据库进行标记。 –

回答

3

在你可以做这样的事情大多数数据库:

Select * 
from testTable 
order by abs(width - 10.3) 
fetch first 1 row only; 

某些数据库可能使用limit,top,甚至where rownum = 1,但这个想法是一样的。

1

你会写这样的事:

select * from (
    Select * from testTable where width = 10.3 
    union 
    Select * from testTable where width > 10.1 and width < 10.9 
    order by abs (10.3 - width) asc 
) T LIMIT 1 

是的,它可以降低到什么Gordon Linoff显示

Select * from testTable where width > 10.1 and width < 10.9 
    order by abs (10.3 - width) asc 
    LIMIT 1