【问题标题】:UPDATE statement in SQLite with nested FROM and JOINSQLite 中带有嵌套 FROM 和 JOIN 的 UPDATE 语句
【发布时间】:2018-12-26 17:42:11
【问题描述】:

我目前有一条 SQL 语句:

UPDATE table_1 SET
  property_1=b.value_1,
  property_2=b.value_2,
  property_3=b.value_3
FROM (
  SELECT a.property_4, a.property_5, b.value_2, b.value_3
  FROM (
    SELECT id1 AS property_4, MAX(id2) AS property_5
    FROM table_2
    WHERE
      id1 IN (...) AND
      id2 NOT IN (...)
    ) a
    JOIN table_3 b ON
      a.property_5 = b.id
) a
WHERE
table_1.id = a.property_4

这在我们的生产 postgresql db 上运行良好,但是 UPDATE 的语法在 SQLite 中是不同的(我们在测试中使用的),我发现我自己对如何转换它很困惑。我收到的错误是Error: syntax error near FROM。如果有人是 SQLite 高手,我将不胜感激。

【问题讨论】:

    标签: sql postgresql sqlite


    【解决方案1】:

    由于 SQLite 不支持带有 JOIN/FROM 子句的 UPDATE。您可以使用CTE & SubQuery 交替进行:

    WITH cte AS (
        SELECT a.property_4, b.value_1, b.value_2, b.value_3
        FROM (
        SELECT id1 AS property_4, MAX(id2) AS property_5
        FROM table_2
        WHERE
          id1 IN (...) AND
          id2 NOT IN (...)
        ) a 
        JOIN table_3 b ON
        a.property_5 = b.id    
    )
    
    UPDATE table_1 SET
      property_1=(select value_1 from cte where cte.property_4 = id)
      property_2=(select value_2 from cte where cte.property_4 = id)
      property_3=(select value_3 from cte where cte.property_4 = id)
    WHERE
    id IN (select property_4 from cte)
    

    【讨论】:

    • 这非常有效!非常感谢!需要注意的是,由于我们使用CTE,我们没有指定b.value_1、b.value_2、b.value_3,我们只使用value_1、value_2、value_3。
    猜你喜欢
    • 1970-01-01
    • 2012-10-09
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    • 2021-10-17
    相关资源
    最近更新 更多