如何在SQLite中使用相关子查询更新多个列?

如何在SQLite中使用相关子查询更新多个列?,sqlite,sql-update,Sqlite,Sql Update,我想使用相关子查询更新表中的多个列。更新单个列非常简单: UPDATE route SET temperature = (SELECT amb_temp.temperature FROM amb_temp.temperature WHERE amb_temp.location = route.location) 但是,我想更新路由表的几列。由于子查询在现实中要复杂得多(使用函数与嵌套子查询连接),我希望避免像这样重复它

我想使用相关子查询更新表中的多个列。更新单个列非常简单:

UPDATE route
SET temperature = (SELECT amb_temp.temperature
                   FROM amb_temp.temperature
                   WHERE amb_temp.location = route.location)
但是,我想更新路由表的几列。由于子查询在现实中要复杂得多(使用函数与嵌套子查询连接),我希望避免像这样重复它:

UPDATE route
SET
  temperature = (SELECT amb_temp.temperature
                 FROM amb_temp.temperature
                 WHERE amb_temp.location = route.location),
  error = (SELECT amb_temp.error
           FROM amb_temp.temperature
           WHERE amb_temp.location = route.location),
UPDATE route
SET (temperature, error) = (SELECT amb_temp.temperature, amb_temp.error
                            FROM amb_temp.temperature
                            WHERE amb_temp.location = route.location)
理想情况下,SQLite会让我这样做:

UPDATE route
SET
  temperature = (SELECT amb_temp.temperature
                 FROM amb_temp.temperature
                 WHERE amb_temp.location = route.location),
  error = (SELECT amb_temp.error
           FROM amb_temp.temperature
           WHERE amb_temp.location = route.location),
UPDATE route
SET (temperature, error) = (SELECT amb_temp.temperature, amb_temp.error
                            FROM amb_temp.temperature
                            WHERE amb_temp.location = route.location)
唉,这是不可能的。这能用另一种方法解决吗

以下是我到目前为止一直在考虑的:

  • 按照中的建议使用插入或替换。似乎不可能在子查询中引用路由表
  • 在UPDATE查询前面加上一个,但我认为这在这种情况下没有用处
为了完整起见,下面是我正在处理的实际SQL查询:

UPDATE route SET (temperature, time_distance) = ( -- (C)
  SELECT  -- (B)
    temperature.Temp,
    MIN(ABS(julianday(temperature.Date_HrMn)
            - julianday(route.date_time))) AS datetime_dist
  FROM temperature
    JOIN (
      SELECT  -- (A)
        *, Distance(stations.geometry,route.geometry) AS distance
      FROM stations
      WHERE EXISTS (
        SELECT 1
        FROM temperature
        WHERE stations.USAF = temperature.USAF
              AND stations.WBAN_ID = temperature.NCDC
        LIMIT 1
      )
      GROUP BY stations.geometry
      ORDER BY distance
      LIMIT 1
  ) tmp
  ON tmp.USAF = temperature.USAF
     AND tmp.WBAN_ID = temperature.NCDC
)
此查询的高级描述:

  • 使用
    路线
    表中的
    几何图形(=经度和纬度)和
    日期时间
  • (A) 查找气象站(
    表,由USAF和NCDC/WBAN\U ID列唯一标识)
    • 最接近给定经度/纬度(
      几何体
    • 温度出现在
      温度表中
  • (B) 查找
    温度
    表格行
    • 上面的气象站
    • 最接近给定时间戳的时间
  • (C) 将温度和“时间距离”存储在
    路线表中

您可以将没有关联的子查询放入WITH中,然后使用简单的关联子查询从中进行选择。对于我添加到问题中的实际SQL查询,这可能吗?这不会慢很多吗?