根据SELECT计算值更新表

时间:2015-03-02 18:21:15

标签: mysql sql

cities

| 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       |                      |

我已经有一个查询通过使用cities表和hotels表中的值来产生距离(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

任何提示赞赏。

1 个答案:

答案 0 :(得分:0)

SET

之后移动JOIN
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