你可以在SQLAlchemy中执行没有子查询的UNION吗?

时间:2016-04-26 21:29:02

标签: sqlalchemy

Another question shows how to do a union in SQLAlchemy.

是否可以在不使用子查询的情况下在SQLAlchemy中执行联合?

例如,在链接的问题中,SQLAlchemy生成以下形式的SQL:

SELECT * FROM (SELECT column_a FROM table_a UNION SELECT column_b FROM table_b)

但我希望SQLAlchemy能够生成如下的SQL:

SELECT column_a FROM table_a UNION SELECT column_b FROM table_b

后者SQL更短,不使用子查询,并做同样的事情。 SQLAlchemy可以生成像后一个查询一样的联合吗?

1 个答案:

答案 0 :(得分:1)

根据SQLAlchemy SQL Expression Language Tutorial

您可以使用sqlalchemy.sql.expression.union

>>> from sqlalchemy.sql import union
>>> u = union(
...     addresses.select().
...             where(addresses.c.email_address == 'foo@bar.com'),
...    addresses.select().
...             where(addresses.c.email_address.like('%@yahoo.com')),
... ).order_by(addresses.c.email_address)

>>> u.compile()
SELECT addresses.id, addresses.user_id, addresses.email_address FROM
addresses WHERE addresses.email_address = ?
UNION
SELECT addresses.id,
addresses.user_id, addresses.email_address FROM addresses WHERE
addresses.email_address LIKE ? ORDER BY addresses.email_address
('foo@bar.com', '%@yahoo.com')