UPDATE语句和WITH子句

时间:2013-11-05 16:45:11

标签: sql postgresql

我想使用WITH子句更新我的表。 我在努力:

UPDATE mytable 
SET myfield = (
   WITH sub AS (SELECT 18) 
   SELECT CASE WHEN (sub = 18) THEN 100 ELSE 0 END)

WITH sub AS (SELECT 18)
UPDATE mytable 
SET myfield = ( 
   SELECT CASE WHEN (sub = 18) THEN 100 ELSE 0 END)

但它不起作用。请向我解释我做错了什么。

3 个答案:

答案 0 :(得分:1)

您的sub是记录集,而不是列。这个可行:

with sub(col) as (select 18)
update mytable set
   myfield = (select case when col = 18 then 100 else 0 end from sub)

但是它会用{更新mytable中的所有行。不知道你想对你的查询做什么,所以不能更准确。

答案 1 :(得分:0)

UPDATE mytable 
SET myfield = (
   WITH sub AS (SELECT 18 AS field) 
   SELECT CASE WHEN (field = 18) THEN 100 ELSE 0 END
   FROM sub)

答案 2 :(得分:0)

WITH子句定义“公用表表达式”,并在后续查询中视为表。所以,您仍然需要在后续查询中引用公用表表达式名称,就像在表中一样,我发现更明确的是在CTE名称前加上cte_只是为了使它在复杂表达式中清楚地说明了源代码是什么。数据是。

update mytable 
set    myfield = (
         with cte_sub as
           (select 18 as field) 
         select case field
                  when 18 then 100
                  else 0
                end
         from cte_sub)