python - 在 Postres SqlAlchemy 中加入 CTE(With 子句)
问题描述
我正在努力WITH AS VALUES
在 SqlAlchemy 中编写一个子句。
让我们假设下表
CREATE TABLE Example ("name" varchar(5), "level" varchar(5));
INSERT INTO Example ("name", "level") VALUES
('John', 'one'),
('Alice', 'two'),
('Bob', 'three')
;
在查询中,我现在想用数字替换级别名称
WITH matched_levels (level_name, level_score) as (
values ('one', 1.0),
('two', 2.0),
('three', 3.0)
)
select e.name, m.level_score
from Example e
join matched_levels m on e.level = m.level_name;
-- name level_score
-- John 1
-- Alice 2
-- Bob 3
另请参阅此 SQL fiddle。
我怎样才能在 SqlAlchemy 中写这个?
在我发现的其他 SO 问题([1]、[2]、[3])之后,我想出了以下内容
matching_levels = sa.select([sa.column('level_name'), sa.column('level_score')]).select_from(
sa.text("values ('one', 1.0), ('two', 2.0), ('three', 3.0)")) \
.cte(name='matched_levels')
result = session.query(Example).join(
matching_levels,
matching_levels.c.level_name == Example.level
).all()
这转化为这个不起作用的查询
WITH matched_levels AS
(SELECT level_name, level_score
FROM values ('one', 1.0), ('two', 2.0), ('three', 3.0))
SELECT "Example".id AS "Example_id", "Example".name AS "Example_name", "Example".level AS "Example_level"
FROM "Example" JOIN matched_levels ON matched_levels.level_name = "Example".level
链接
解决方案
根据这个答案:
您可以尝试以matching_levels
这种方式重写您的查询:
matching_levels = select(Values(
column('level_name', String),
column('level_score', Float),
name='temp_table').data([('one', 1.0), ('two', 2.0), ('three', 3.0)])
).cte('matched_levels')
result = session.query(Example).join(
matching_levels,
matching_levels.c.level_name == Example.level
).all()
推荐阅读
- java - Cactoos flatMap 类比
- ios - 使用领域时出现间歇性链接器和构建错误
- xslt - 如何在 TIBCO 的 Transform xml 活动的输出中获取与号“&”
- jquery - 更改点击功能上的图标
- visual-studio-code - Visual Studio 代码中的增量搜索快捷方式
- mysql - 为什么当我用 mysql 数据库调试我的应用程序胶子时,我的手机没有打开?
- amazon-web-services - 解读 AWS Glue 内存不足和指标
- python - Running session failed due to tensors datatype and shape Tensorflow
- c++ - OpenGL用鼠标移动顶点
- excel - 命令条代码在标准模块中有效,但在“ThisWorkbook”模块中无效