2017-06-27 58 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