[英]How to move CTE for oracle update query in sqlalchemy
我面臨着Oracle錯誤ORA-00928: missing SELECT keyword
生成的查詢ORA-00928: missing SELECT keyword
。 該問題已在此處描述並得到解答。
我的查詢看起來像:
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)
)
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
)
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.