Ank
Ank

Reputation: 1904

MySQL Select multiple rows with almost same value

I am using python and MySQL and I have the following table:

id    name    value1    value2
1     a       36041     140636
2     b       36046     140647
3     c       36042     140642
4     d       36042     140645
5     e       36040     140642

I want to select all those rows which have almost same value1 and value2 (±2). So based on the table above, I want to select row 3 and row 5 only and arrange them in increasing order of value1. How should I write the SELECT query for this?

Upvotes: 0

Views: 131

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1270463

I think you want a self join:

select t1.*, t2.*
from t t1 join
     t t2
     on abs(t1.value1 - t2.value1) <= 2 and
        abs(t1.value2 - t2.value2) <= 2 and
        t1.id < t2.id
order by t1.value1

Upvotes: 1

Blank
Blank

Reputation: 12378

One way to achieve this by using self-join:

select t1.*
from table1 t1
join table1 t2
on abs(t1.value1 - t2.value1) <= 2
and abs(t1.value2 - t2.value2) <= 2
and t1.id <> t2.id
order by t1.value1

And see demo in Rextester.

Upvotes: 1

Related Questions