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

问题描述 投票:0回答:1

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

UPDATE route
SET temperature = (SELECT amb_temp.temperature
                   FROM amb_temp.temperature
                   WHERE amb_temp.location = route.location)

但是,我想更新路由表的几列。由于子查询实际上要复杂得多(使用 SpatiaLite 函数连接嵌套子查询),我想避免像这样重复它:

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

理想情况下,SQLite 会让我做这样的事情:

UPDATE route
SET (temperature, error) = (SELECT amb_temp.temperature, amb_temp.error
                            FROM amb_temp.temperature
                            WHERE amb_temp.location = route.location)

唉,这是不可能的。可以用其他方法解决吗?

这是我到目前为止一直在考虑的事情:

  • 按照此答案中的建议使用插入或替换。子查询中似乎无法引用路由表。
  • 在 UPDATE 查询前面加上 WITH 子句,但我认为这在这种情况下没有用。

为了完整起见,这是我正在处理的实际 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
)

此查询的高级描述:

  • 使用
    geometry
    表中的
    date_time
    (= 经度和纬度)和
    route
  • (A) 找到气象站(
    stations
    表,由 USAF 和 NCDC/WBAN_ID 列唯一标识)
    • 最接近给定的经度/纬度 (
      geometry
      )
    • temperature
      表中列出了哪些温度
  • (B) 找到
    temperature
    表格行
    • 对于上面找到的气象站
    • 最接近给定时间戳的时间
  • (C) 将温度和“时间_距离”存储在
    route
    表中
sqlite sql-update
1个回答
0
投票
UPDATE route
SET
  temperature = q.temperature,
  error = q.error
FROM ( SELECT * FROM amb_temp ) q
WHERE q.location = route.location

© www.soinside.com 2019 - 2024. All rights reserved.