在更新的WHERE条件下引用CTE

时间:2018-12-03 10:16:32

标签: mysql sql common-table-expression

我正在尝试运行这样的查询:

WITH cte AS
(
  SELECT id, category, SUM(amount) AS sum_amount FROM t1 GROUP BY id, category
)
UPDATE table SET amount = cte.sum_amount WHERE id = cte.id;

但是,我不断收到错误消息

Unknown column 'cte.id in WHERE clause'

有人知道我如何在UPDATE查询中引用我的公用表表达式,否则可以重写它?

2 个答案:

答案 0 :(得分:2)

您可以在下面尝试

WITH cte AS
(
  SELECT id, SUM(amount) AS sum_amount FROM t1 GROUP BY category
)
UPDATE T
SET  T.sum_amount= CT.sum_amount
FROM table T
JOIN cte CT
     ON T.id = CT.id

答案 1 :(得分:0)

Alternate way with Temporary table, you can read about CTE and Temporary Table

Temporary table:

SELECT id, category, SUM(amount) AS sum_amount 
INTO #temp
FROM t1 GROUP BY id, category

Update query with temp table:

UPDATE OT
SET  OT.sum_amount= TT.sum_amount
FROM table OT
JOIN #temp TT
    ON OT.id = TT.id

CTE:

WITH cte AS
(
  SELECT id, category, SUM(amount) AS sum_amount FROM t1 GROUP BY id,category
)
UPDATE T
SET T.sum_amount= CT.sum_amount
FROM table T
JOIN cte CT
    ON T.id = CT.id