简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM