dbTalk Databases Forums  

How to SELECT the most approximated value?

comp.databases.mysql comp.databases.mysql


Discuss How to SELECT the most approximated value? in the comp.databases.mysql forum.



Reply
 
Thread Tools Display Modes
  #1  
Old   
Rafael Patro
 
Posts: n/a

Default How to SELECT the most approximated value? - 07-04-2010 , 10:45 AM






I have an integer column, and I want to search a value that could not
be there.
Example column values: 114,54,223,67,187,991
Example search value: 100

How to find row 100 (if exists) or the most approximated value 114?

My actual solution is:
SELECT * FROM table WHERE column < search ORDER BY column DESC LIMIT
0,1
SELECT * FROM table WHERE column > search ORDER BY column DESC LIMIT
0,1

But my doubt is: Is there any function to do this in MySQL?

Reply With Quote
  #2  
Old   
Lennart Jonsson
 
Posts: n/a

Default Re: How to SELECT the most approximated value? - 07-04-2010 , 10:54 AM






On 2010-07-04 16:45, Rafael Patro wrote:
Quote:
I have an integer column, and I want to search a value that could not
be there.
Example column values: 114,54,223,67,187,991
Example search value: 100

How to find row 100 (if exists) or the most approximated value 114?

My actual solution is:
SELECT * FROM table WHERE column < search ORDER BY column DESC LIMIT
0,1
SELECT * FROM table WHERE column > search ORDER BY column DESC LIMIT
0,1

But my doubt is: Is there any function to do this in MySQL?
Here's one way to do it:

create table tt ( x int not null primary key ) engine = innodb;
insert into tt (x) values (114),(54),(223),(67),(187),(991);

select tt.x
from tt
join (
select min(abs(x-100)) as y
from tt
) as t2
on abs(tt.x-100) = t2.y;

+-----+
Quote:
x |
+-----+
114 |
+-----+

/Lennart

Reply With Quote
Reply




Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off



Powered by vBulletin Version 3.5.3
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.