【发布时间】:2020-08-28 13:42:04
【问题描述】:
我正在努力在 SqlAlchemy 中编写 WITH AS VALUES 子句。
假设如下表
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
如何在 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
链接
【问题讨论】:
标签: python sql postgresql sqlalchemy common-table-expression