2015-03-02 73 views
1

cities更新基于SELECT计算值的表

| id | lat  | lon  | 
|----|------------|-----------| 
| 1 | 34.44444 | 84.3434 | 
| 2 | 42.4666667 | 1.4666667 | 
| 3 | 32.534167 | 66.078056 | 

hotels

| id | lat  | lon  | city_id | distance_from_center | 
|----|------------|-----------|---------|----------------------| 
| 1 | 33.23444 | 81.2134 | 1  |      | 
| 2 | 41.4666667 | 1.3566667 | 1  |      | 
| 3 | 34.4666667 | 63.178056 | 1  |      | 
| 4 | 37.4666667 | 81.2134 | 2  |      | 
| 5 | 31.4666667 | 1.3566667 | 2  |      | 
| 6 | 41.4666667 | 1.3566667 | 2  |      | 
| 7 | 38.4666667 | 81.2134 | 3  |      | 
| 8 | 37.4434666 | 1.3566667 | 3  |      | 
| 9 | 41.4666667 | 1.3566667 | 3  |      | 
| 10 | 41.4666667 | 81.2134 | 3  |      | 

我已经有其通过使用从城市表和酒店的值产生距离(km)的查询表:

SELECT 
TRUNCATE(111.1111 * DEGREES(ACOS(COS(RADIANS(hotel_lat)) 
     * COS(RADIANS(city_lat)) 
     * COS(RADIANS(hotel_lon) - RADIANS(city_lon)) + SIN(RADIANS(hotel_lat)) 
     * SIN(RADIANS(city_lat)))),2) 
    AS distance_in_km 
FROM hotels 
LEFT JOIN cities ON hotels.city_id = cities.id 

现在我想运行查询,以便它会根据距离自动更新酒店表中的所有值。

这是我的尝试,但它产生的SQL语法错误:

UPDATE hotels 
SET distance_from_center = dist 
FROM (
    SELECT 
     hotels.id as hid, 
     TRUNCATE(111.1111 * DEGREES(ACOS(COS(RADIANS(hotel_lat)) 
      * COS(RADIANS(city_lat)) 
      * COS(RADIANS(hotel_lon) - RADIANS(city_lon)) + SIN(RADIANS(hotel_lat)) 
      * SIN(RADIANS(city_lat)))),2) 
     AS dist 
    FROM hotels 
    LEFT JOIN cities ON hotels.city_id = cities.id 
    GROUP BY hid 
) t2 
WHERE hotels.id = t2.hid 

任何提示赞赏。

回答

0

移动的SETJOIN

UPDATE hotels 
JOIN (
    SELECT 
     hotels.id as hid, 
     TRUNCATE(111.1111 * DEGREES(ACOS(COS(RADIANS(hotel_lat)) 
      * COS(RADIANS(city_lat)) 
      * COS(RADIANS(hotel_lon) - RADIANS(city_lon)) + SIN(RADIANS(hotel_lat)) 
      * SIN(RADIANS(city_lat)))),2) 
     AS dist 
    FROM hotels 
    LEFT JOIN cities ON hotels.city_id = cities.id 
    GROUP BY hid 
) t2 ON hotels.id = t2.hid 
SET distance_from_center = dist 

MySQL的多表更新的语法格式如下:

update table1 
[left] join table2 on <condition> 
-- optionally more joins 
set someTable.someColumn = <some expession using anything from any table> 
-- optionally more sets 
-- optionally a where clause 
+0

效果很好,第一个版本不;)感谢的确认句法。 – digout 2015-03-02 18:52:43