我用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)
)
发布于 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
)
);
https://stackoverflow.com/questions/56061391
复制相似问题