So the way to do this is to run both queries and take the UNION from the sets. It. Actually there is very little performance loss because the first set (which can produce> 5 rows) is already required if the result is really more than 5 rows.
More details - original answer below
To illustrate, instead of using 2 datasets, I just use 2 columns in the same sample table, for which the query is shown below:
drop table if exists tbl1; create table tbl1 ( id int, name varchar(100), distance1 float, distance2 float ); insert tbl1 values ( 3 , 'Earl of Sandwich ', 0.3, 0.1), ( 4 , 'Nails ''n More ', 0.8, 0.2), ( 22 , 'City Hotel ', 1.7, 1.7), ( 5 , 'Mighty Medicine ', 2.1, 0.5), ( 25 , 'Wonder Wings ', 2.5, 2.1), ( 6 , 'Jean Warehouse ', 2.7, 0.7), ( 9 , 'Ship Safe & Speedy ', 2.9, 0.9), ( 2 , 'Bagel Bonus ', 4.1, 1.2);
And queries and results:
select id, name, distance1 from ( select * from tbl1 where distance1 <= 2.0 order by distance1) a union select id, name, distance1 from ( select * from tbl1 order by distance1 limit 5) b; id;name;distance1 3;Earl of Sandwich ;0.3 4;Nails 'n More ;0.8 22;City Hotel ;1.7 5;Mighty Medicine ;2.1 25;Wonder Wings ;2.5 select id, name, distance2 from ( select * from tbl1 where distance2 <= 2.0 order by distance2) a union select id, name, distance2 from ( select * from tbl1 order by distance2 limit 5) b; id;name;distance2 3;Earl of Sandwich ;0.1 4;Nails 'n More ;0.2 5;Mighty Medicine ;0.5 6;Jean Warehouse ;0.7 9;Ship Safe & Speedy ;0.9 2;Bagel Bonus ;1.2 22;City Hotel ;1.7
The performance of this query is as good as it gets.
The first part of the UNION chooses those that are 2 km away. This is necessary since you want all matches.
The next part selects the top five and assuming you have an index, this is trivial to collect. The combination (UNION) of both parts is very fast.