如何在sqlalchemy中为oracle更新查询移动CTE

2024-04-27 04:56:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正面临一个由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)
)

Tags: infromidaswithexiststableupdate
1条回答
网友
1楼 · 发布于 2024-04-27 04:56:55

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

或者,使用old语法,表(在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
                            )
               );

相关问题 更多 >