首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在sqlalchemy中为oracle update查询移动CTE

如何在sqlalchemy中为oracle update查询移动CTE
EN

Stack Overflow用户
提问于 2019-05-09 22:11:58
回答 1查看 240关注 0票数 2

我用sqlalchemy生成的查询来面对oracle错误ORA-00928: missing SELECT keyword。这个问题已经描述过了,并回答了here

我的查询如下所示:

WITH table2 (id) AS (
    SELECT id
    FROM table3
)

UPDATE table SET id=1 
WHERE EXISTS (
    SELECT * 
    FROM table 
    WHERE id IN (SELECT id FROM table2)
)

并通过下面的代码生成:

table2 = session.query(table3.id).cte()
update(table).where(exists().where(table.id.in_(table2))).values(id=1)

现在我想知道如何告诉sqlachemy将CTE放在WHERE子句中,而不是放在UPDATE之上。

UPDATE table SET id=1 
WHERE EXISTS (
    WITH table2 (id) AS (
        SELECT id
        FROM table3
    )

    SELECT * 
    FROM table 
    WHERE id IN (SELECT id FROM table2)
)
EN

回答 1

Stack Overflow用户

发布于 2019-05-10 03:44:16

CTE是从查询中提取内联视图的一种很好的方法,这样做可以使代码更易于阅读和维护。

当CTE还没有发明的时候,我们使用内联视图。这里有几个例子(基于Scott的模式)来说明我的意思。

首先,CTE:

SQL> with tab as
  2    (select deptno from dept
  3     where deptno > 10
  4    )
  5  select e.deptno, count(*)
  6  from emp e join tab t on t.deptno = e.deptno
  7  group by e.deptno;

    DEPTNO   COUNT(*)
---------- ----------
        30          6
        20          5

可以将其移动到内联视图中:

SQL> select e.deptno, count(*)
  2  from emp e join (select deptno from dept
  3                   where deptno > 10
  4                  ) t on t.deptno = e.deptno
  5  group by e.deptno;

    DEPTNO   COUNT(*)
---------- ----------
        30          6
        20          5

或者,使用旧语法,其中表(在FROM子句中)用逗号分隔,连接在WHERE子句中完成(这可能看起来很熟悉):

SQL> select e.deptno, count(*)
  2  from emp e,
  3      (select deptno from dept
  4       where deptno > 10
  5      ) t
  6  where t.deptno = e.deptno
  7  group by e.deptno;

    DEPTNO   COUNT(*)
---------- ----------
        30          6
        20          5

这意味着您的查询可能如下所示;请注意显示CTE位置的注释:

update table set
  id = 1
  where exists (select *
                from table
                where id in (select id 
                             from 
                               (select id from table3)  --> this line is your CTE
                            )
               );
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56061391

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档