SQLite中带有嵌套FROM和JOIN的UPDATE语句

时间:2018-07-18 17:49:45

标签: sql postgresql sqlite

我目前有一个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专家,我将不胜感激一些指导。

1 个答案:

答案 0 :(得分:1)

由于SQLite不支持JOIN / FROM子句进行UPDATE。您可以使用CTESubQuery来替代:

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)