Oracle PL/SQL – Find Nearest Object

nearest neighbororacle-12cplsql

There are two tables containing objects and their coordinates. One contains hotels, the other contains restaurants. How to build a table that for each hotel lists nearest restaurant name and the distance?

WITH restaurant AS (
           SELECT 'A' r_name, 0.0 x, 0.0 y FROM dual UNION ALL
           SELECT 'B' r_name, 0.0 x, 6.0 y FROM dual UNION ALL
           SELECT 'C' r_name, 9.5 x, 0.5 y FROM dual UNION ALL
           SELECT 'D' r_name, 8.2 x, 4.7 y FROM dual -- etc           
           ),

     hotel AS ( 
           SELECT 'First_Hotel' h_name, 1.0 x, 6.0 y FROM dual UNION ALL  
           SELECT 'Second_Hotel' h_name, -4.0 x, 3.0 y FROM dual -- etc
           )               

     select h.h_name, r.r_name as nearest_restaurant, distance from restaurant r, hotel h  /* some query */

Should return

 hotel          nearest_restaurant    distance
 First_Hotel       B                    1     -- B is the nearest restaurant to First_Hotel. Distance is sqrt((1.0-0.0)^2+(6.0-6.0)^2)=1
 Second_Hotel      A                    5     --if both A and B on the same distance choose based on r_name 

Edited: I also have geoloc for both tables with x and y coordinates. Can geoloc help to build the query?

Best Answer

This query worked for me. It uses GEOLOC from Oracle Spartial

    create table my_result_table as  (
    select n.nodeid, n.geoloc.sdo_point.y as node_y, n.geoloc.sdo_point.x as node_x, 
        r.geoloc.sdo_point.y as sl_y, r.geoloc.sdo_point.x as sl_x,
        sdo_nn_distance(1)  as sld
       from  my_nodes n,  my_restaurants r
       where
       sdo_nn   ( r.GEOLOC, n.geoloc,  'Unit = MILE sdo_num_res = 1', 1) = 'TRUE'
        );

Note that first argument is restaurants, not nodes.