在Postres SqlAlchemy中加入CTEWith子句

问题描述

我正在努力在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

另请参阅this 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',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',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

链接

解决方法

根据此answer

您可以尝试以这种方式重写您的 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()