SQLAlchemy中的正确的外部联接

时间:2012-07-09 17:46:14

标签: python sql sqlalchemy

我在下面定义了两个表beardmoustache

+--------+---------+------------+-------------+
| person | beardID | beardStyle | beardLength |
+--------+---------+------------+-------------+

+--------+-------------+----------------+
| person | moustacheID | moustacheStyle |
+--------+-------------+----------------+

我在PostgreSQL中创建了一个SQL查询,它将组合这两个表并生成以下结果:

+--------+---------+------------+-------------+-------------+----------------+
| person | beardID | beardStyle | beardLength | moustacheID | moustacheStyle |
+--------+---------+------------+-------------+-------------+----------------+
| bob    | 1       | rasputin   | 1           |             |                |
+--------+---------+------------+-------------+-------------+----------------+
| bob    | 2       | samson     | 12          |             |                |
+--------+---------+------------+-------------+-------------+----------------+
| bob    |         |            |             | 1           | fu manchu      |
+--------+---------+------------+-------------+-------------+----------------+

查询:

SELECT * FROM beards LEFT OUTER JOIN mustaches ON (false) WHERE  person = "bob"
UNION ALL
SELECT * FROM beards b RIGHT OUTER JOIN mustaches ON (false) WHERE  person = "bob"

但是我无法创建它的SQLAlchemy表示。我尝试了从实现from_statementouterjoin的几种方法,但它们都没有真正起作用。任何人都可以帮我吗?

5 个答案:

答案 0 :(得分:3)

@Francis Psuggestion我想出了这个片段:

q1 = session.\
     query(beard.person.label('person'),
           beard.beardID.label('beardID'),
           beard.beardStyle.label('beardStyle'),
           sqlalchemy.sql.null().label('moustachID'),
           sqlalchemy.sql.null().label('moustachStyle'),
     ).\
     filter(beard.person == 'bob')

q2 = session.\
     query(moustache.person.label('person'),
           sqlalchemy.sql.null().label('beardID'), 
           sqlalchemy.sql.null().label('beardStyle'),
           moustache.moustachID,
           moustache.moustachStyle,
     ).\
     filter(moustache.person == 'bob')

result = q1.union(q2).all()

然而,这可行,但您不能将其称为答案,因为它看起来像一个黑客。这是sqlalchemy中应该有RIGHT OUTER JOIN的另一个原因。

答案 1 :(得分:2)

在SQL中,可以将A RIGHT OUTER JOIN B替换为B LEFT OUTER JOIN A,以获得相同的结果。因此,您实际上并不需要在API中显式地使用RIGHT OUTER JOIN,而是可以通过切换目标“可选”和加入“可选”的位置来实现相同的目的。 SQL Alchemy为此提供了一个API:

也就是说:

# this **fictional** API:
query(A).join(B, right_outer_join=True)  # right_outer_join doesn't exist in SQLA!

# can be implemented in SQLA like this:
query(A).select_entity_from(B).join(A, isouter=True)

请参见SQLA Query.join() doc,第“控制要加入的内容”部分

答案 2 :(得分:2)

如果A,B是表,则可以实现:
SELECT * FROM A RIGHT JOIN B ON A.id = B.a_id WHERE B.id = my_id
创建人:
SELECT A.* FROM B JOIN ON A.id = B.a_id WHERE B.id = my_id
在sqlalchemy中:

from sqlalchemy import select


result = session.query(A).select_entity_from(select([B]))\
    .join(A, A.id == B.a_id)\
    .filter(B.id == my_id).first()

例如:

# import ...

class User(Base):
    __tablenane = "user"

    id = Column(Integer, primary_key=True)
    group_id = Column(Integer, ForeignKey("group.id"))

class Group(Base):
    __tablename = "group"

    id = Column(Integer, primary_key=True)
    name = Column(String(100))

您可以使用以下代码通过用户ID获取用户组名称:

# import ...
from sqlalchemy import select

user_group_name, = session.query(Group.name)\
    .select_entity_from(select([User]))\
    .join(Group, User.group_id == Group.id)\
    .filter(User.id == 1).first()

如果要进行外部联接,请使用outerjoin()而不是join()

此答案是对前一个答案(Timur的答案)的补充。

答案 3 :(得分:1)

这就是我所拥有的,ORM风格:

from sqlalchemy.sql import select, false

stmt = (
    select([Beard, Moustache])
    .select_from(
        outerjoin(Beard, Moustache, false())
    ).apply_labels()
).union_all(
    select([Beard, Moustache])
    .select_from(
        outerjoin(Moustache, Beard, false())
    ).apply_labels()
)

session.query(Beard, Moustache).select_entity_from(stmt)

这似乎对它有效,但似乎无法加入另一个选择表达式

答案 4 :(得分:0)

不幸的是,SQLAlchemy仅为LEFT OUTER JOIN提供了.outerjoin()的API。如above所述,我们可以通过反转RIGHT OUTER JOIN的操作数来获得LEFT OUTER JOIN;例如。 A RIGHT JOIN BB LEFT JOIN A相同。 在SQL中,以下语句是等效的:

SELECT * FROM A RIGHT OUTER JOIN B ON A.common = B.common;
SELECT * FROM B LEFT OUTER JOIN A ON A.common = B.common;

但是,在SQLAlchemy中,我们需要查询一个类,然后执行join。棘手的部分是重写SQLAlchemy语句以反转表。例如,下面的前两个查询的结果不同,因为它们返回不同的对象。

# No such API (rightouterjoin()) but this is what we want.
# This should return the result of A RIGHT JOIN B in a list of object A
session.query(A).rightouterjoin(B).all()   # SELECT A.* FROM A RIGHT OUTER JOIN B ...

# We could reverse A and B but this returns a list of object B
session.query(B).outerjoin(A).all()        # SELECT B.* FROM B LEFT OUTER JOIN A ...

# This returns a list of object A by choosing the 'left' side to be B using select_from()
session.query(A).select_from(B).outerjoin(A).all()   # SELECT A.* FROM B LEFT OUTER JOIN A ...

# For OP's example, assuming we want to return a list of beard object:
session.query(beard).select_from(moustache).outerjoin(beard).all()

只需添加答案,您就可以从SQLAlchemy doc中找到select_from的用法。