简体   繁体   English

SQLAlchemy - 带有父查询参数的子查询

[英]SQLAlchemy - subqueries with parameters from parent query

I have the following SQL Statement that I want to convert to SQLAlchemy code:我有以下 SQL 语句要转换为 SQLAlchemy 代码:

SELECT job_type, requirement_type, val = IIF( 
  EXISTS (
    SELECT val
    FROM common.job_config_requirements jcr
    WHERE job_type = jcr.job_type
      AND requirement_type = jcr.requirement_type
  ),
  (
    SELECT COUNT(val)
    FROM common.job_config_requirements jcr
    WHERE jc.job_type = jcr.job_type
      AND jcrt.requirement_type = jcr.requirement_type
  ),
  0
)
FROM common.job_config jc
CROSS JOIN common.job_config_requirement_types jcrt;

I am using SQL Server and would like to know how I can pass the main queries arguments towards the subqueries.我正在使用 SQL 服务器,想知道如何将主查询 arguments 传递给子查询。

Have you tried putting it in the text function?您是否尝试将其放在文本 function 中?

I use the text function when I have large complicated queries.当我有大型复杂查询时,我使用文本 function。

from sqlalchemy import text

select_stm = text('''
    SELECT job_type, requirement_type, val = IIF( 
    EXISTS (
       SELECT val
       FROM common.job_config_requirements jcr
       WHERE job_type = jcr.job_type
       AND requirement_type = jcr.requirement_type
    ),
    (
       SELECT COUNT(val)
       FROM common.job_config_requirements jcr
       WHERE jc.job_type = jcr.job_type
       AND jcrt.requirement_type = jcr.requirement_type
    ),
    0
)
FROM common.job_config jc
CROSS JOIN common.job_config_requirement_types jcrt;
''')

conn.execute(select_stm)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM