SQL Missing Select语句 - 更新Oracle

时间:2017-05-30 21:07:56

标签: sql oracle select

我似乎无法弄清楚这个针对Oracle的SQL代码有什么问题。我试图基于子查询更新数据库。

with T as 
(SELECT "Folder Name", SUM("Session Length") as "Folder Length" 
 FROM "SESSIONUSAGE" 
 GROUP BY "Folder Name")
UPDATE FolderUsage SET ("Folder Length") = 
(SELECT "Folder Length" FROM T
    WHERE (FolderUsage."Folder Name" = T."Folder Name")

我需要这些空间,因为我找到了数据库。谢谢你的帮助!

2 个答案:

答案 0 :(得分:2)

正确的语法是

update FolderUsage
  set "Folder Length" =
    ( 
       with T as ( <aggregate SELECT statement defining T goes here> )
       select "Folder Length" from T where ........
    )

WITH子句属于SELECT语句,它是子查询; WITH子句不会高于UPDATE子句!

但是,在这种情况下,您可以使用MERGE语句做得更好:

merge into FolderUsage F
  using ( <aggregate SELECT statement defining T goes here> ) T
    on (F."Folder Name" = T."Folder Name")
when matched then update set "Folder Length" = T."Folder Length"

答案 1 :(得分:0)

首先,你的括号不平衡:

with T as (
      SELECT "Folder Name", SUM("Session Length") as "Folder Length" 
      FROM "SESSIONUSAGE" 
      GROUP BY "Folder Name"
    )
UPDATE FolderUsage
    SET "Folder Length" = (SELECT "Folder Length"
                           FROM T
                           WHERE FolderUsage."Folder Name" = T."Folder Name"
                          );

但是,甲骨文仍然不会接受这一点。所以,相反:

UPDATE FolderUsage
    SET "Folder Length" = (SELECT SUM(su."Session Length")
                           FROM "SESSIONUSAGE" su
                           WHERE FolderUsage."Folder Name" = su."Folder Name"
                          );

我认为这无论如何都更简单。