【问题标题】:Join CTE (With clause) in Postres SqlAlchemy在 Postgres SqlAlchemy 中加入 CTE(With 子句)
【发布时间】: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

另见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', 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


    【解决方案1】:

    据此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()
    

    【讨论】:

      猜你喜欢
      • 2020-06-08
      • 1970-01-01
      • 1970-01-01
      • 2018-07-07
      • 2021-10-16
      • 1970-01-01
      • 2020-04-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多