簡體   English   中英

將兩個不同的表合並后如何區分特定的列?

[英]How to distinct specific column after union of two different tables?

我想合並兩個不同的表,並使其對於特定列是唯一的。 我正在使用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合並后,我想區分所有記錄。 可能嗎?

預期的輸出將對我來說是相同的,但沒有第一列與另一列相同的項目,第二列為None,例如: [(306, 80, 'StackOverFlow', 'stack@over.flow', 'www.picture.url'), (305, None, 'Google', 'google@gmail.com', ''), (None, 82, 'Explorer', 'explorer@microsoft.com', '')

工作解決方案實際上很簡單。

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM