首页 > 解决方案 > 两个不同表联合后如何区分特定列?

问题描述

我想联合两个不同的表并使其对特定列唯一。我正在使用 postgresql 数据库。

q1 = self.dbsession.query(
            A.id.label('a_id'),
            null().label('b_id'),
            A.name.label('name'),
            A.email.label('email'),
            A.photo.label('photo'))

q2 = self.dbsession.query(
            B.matched_a_id.label('a_id'),
            B.id.label('b_id'),
            B.name.label('name'),
            B.email.label('email'),
            A.photo.label('photo'))

q1.union(q2).all()

这是我得到的输出:

[(306, 80, 'StackOverFlow', 'stack@over.flow', 'www.picture.url'), (306, None, 'StackOverFlow', 'stack@over.flow', 'www.picture.url'), (305, None, 'Google', 'google@gmail.com', ''), (None, 82, 'Explorer', 'explorer@microsoft.com', '')

如您所见,第一项和第二项几乎是重复的。我想在与标记为的第一列合并后区分所有记录a_id。可能吗?

对我来说,预期的输出将是相同的列表,但没有第一列与另一列相同且第二列为无的项目,例如: [(306, 80, 'StackOverFlow', 'stack@over.flow', 'www.picture.url'), (305, None, 'Google', 'google@gmail.com', ''), (None, 82, 'Explorer', 'explorer@microsoft.com', '')

标签: pythonsqlsqlalchemy

解决方案


工作解决方案实际上很容易..

users = self.dbsession.query(
        User.id.label('a_id'),
        null().label('b_id'),
        User.name.label('name'),
        User.email.label('email'),
        User.photo.label('photo'))

invitations = self.dbsession.query(
        ApplicationInvitation.matched_user_id.label('a_id'),
        ApplicationInvitation.id.label('b_id'),
        ApplicationInvitation.name.label('name'),
        ApplicationInvitation.email.label('email'),
        User.photo.label('photo')).\
    filter(ApplicationInvitation.matched_user_id.is(None)).\
    outerjoin(User, ApplicationInvitation.matched_user_id == User.id)

users.union(invitations).all()

推荐阅读