如何在SQLAlchemy和Postgresql中合并两个子查询 [英] How to union two subqueries in SQLAlchemy and postgresql

查看:254
本文介绍了如何在SQLAlchemy和Postgresql中合并两个子查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要原始SQL:

SELECT
    id
FROM
   (SELECT some_table.id FROM some_table WHERE some_table.some_field IS NULL) AS subq1
   UNION
   (SELECT some_table.id WHERE some_table.some_field IS NOT NULL)
LIMIT 10;

这是python代码:

Here is the python code:

import sqlalchemy

SOME_TABLE = sqlalchemy.Table(
 'some_table',
 sqlalchemy.MetaData(),
 sqlalchemy.Column('id', sqlalchemy.Integer, primary_key=True),
 sqlalchemy.Column('some_field', sqlalchemy.Text))

stmt_1 = sqlalchemy.sql.select(SOME_TABLE.columns).where(SOME_TABLE.columns.some_field != None)
stmt_2 = sqlalchemy.sql.select(SOME_TABLE.columns).where(SOME_TABLE.columns.some_field == None)

# This gets a programming error.
stmt_1.union(stmt_2).limit(10);

这是输出的SQL(参数已调入),出现此错误:
错误: UNION处或附近的语法错误:

Here is the outputted SQL (with parameters swapped in) that gets this error: ERROR: syntax error at or near "UNION":

SELECT some_table.id, some_table.some_field
FROM some_table
WHERE some_table.some_field IS NOT NULL
 LIMIT 10 UNION SELECT some_table.id, some_table.some_field
FROM some_table
WHERE some_table.some_field IS NULL
 LIMIT 10
 LIMIT 10

如何别名子查询?

推荐答案

我使用了一些不同的方法:

i used a little bit different approach:

# the first subquery, select all ids from SOME_TABLE where some_field is not NULL
s1 = select([SOME_TABLE.c.id]).where(SOME_TABLE.c.some_field != None)

# the second subquery, select all ids from SOME_TABLE where some_field is NULL
s2 = select([SOME_TABLE.c.id]).where(SOME_TABLE.c.some_field != None)

# union s1 and s2 subqueries together and alias the result as "alias_name"
q = s1.union(s2).alias('alias_name')

# run the query and limit the aliased result to 10
session.query(q).limit(10)

这是生成的sql:

SELECT alias_name.id AS alias_name_id 
FROM (SELECT some_table.id AS id 
FROM some_table 
WHERE some_table.some_field IS NOT NULL UNION SELECT some_table.id AS id 
FROM some_table 
WHERE some_table.some_field IS NULL) AS alias_name 
LIMIT 10

我认为这是您想要的结果。

I think this is the result you wanted.

这篇关于如何在SQLAlchemy和Postgresql中合并两个子查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆