野地表map_resource_node  有两个字段 x,y ,city_id, x,y有值 ,city_id为空值,有1000数据
城堡表 city 有两个字段 x,y 有100数据
需求:现要通过
SQL语句查询出离野地点map_resource_node 最近的城堡city 并更新map_resource_node 表的city_id字段(填写相应的值)我写了个方法但只能一个一个查,并且还不能更新,如下:
select mrns.id,cs.id from power((cs.x-mrns.x),2)+power((cs.y-mrns.y),2)=(select min(power((c.x-mrn.x),2)+power((c.y-mrn.y),2)) where mrn.id=4007) and mrns.id=40074007代表一个野地点的ID,
查询出来的结果为:
野地ID 城堡ID
4007   425我希望能查询出所有野地点ID和最相近的城市ID的结果,并更新到map_resource_node 的相关野地点的city_id中去。

解决方案 »

  1.   


    mysql> select * from map_resource_node;
    +------+------+------+---------+
    | id   | x    | y    | city_id |
    +------+------+------+---------+
    |    1 |   11 |   10 |    NULL |
    |    2 |   30 |   25 |    NULL |
    |    3 |   40 |   34 |    NULL |
    +------+------+------+---------+
    3 rows in set (0.00 sec)mysql> select * from city;
    +------+------+------+
    | id   | x    | y    |
    +------+------+------+
    |    1 |   20 |   14 |
    |    2 |   30 |   10 |
    |    3 |   13 |   45 |
    +------+------+------+
    3 rows in set (0.00 sec)
    mysql> update map_resource_node map_node inner join(
        -> select c.id cid,map.id mid from city c,map_resource_node map
        -> where not exists(
        -> select 1 from city ct,map_resource_node m
        -> where m.id=map.id and
        -> power(ct.x-m.x,2)+power(ct.y-m.y,2)<
        -> power(c.x-map.x,2)+power(c.y-map.y,2))) map_city
        -> on map_node.id=map_city.mid
        -> set map_node.city_id=map_city.cid;
    Query OK, 3 rows affected (0.06 sec)
    Rows matched: 3  Changed: 3  Warnings: 0mysql> select * from map_resource_node;
    +------+------+------+---------+
    | id   | x    | y    | city_id |
    +------+------+------+---------+
    |    1 |   11 |   10 |       1 |
    |    2 |   30 |   25 |       1 |
    |    3 |   40 |   34 |       2 |
    +------+------+------+---------+
    3 rows in set (0.00 sec)
      

  2.   

    离野地点map_resource_node 最近的城堡city------------------------------------
    首先说明你这个“最近”的需求是怎样定义的?从你上面看x、y是不是表示横、纵坐标?