python - 两个不同表联合后如何区分特定列?
问题描述
我想联合两个不同的表并使其对特定列唯一。我正在使用 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', '')
解决方案
工作解决方案实际上很容易..
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()
推荐阅读
- image - IIS - 在 html 中服务器图像放置拒绝直接 url 访问
- java - Android 应用程序错误没有为片段的 id(..) 找到视图
- sql - SQL 查询 - 重复结果 5 次,删除结果集的每个信誉的第一行
- python - 在 python 中的 Flask 和 Web Socket 中出现“无法腌制本地对象”错误
- java - 用spring数据点燃jpa使用语法IN
- html - SVG在旋转时移动位置
- optimization - 使用 CVXOPT 的最小交易规模 - 摆脱可忽略不计的权重
- reactjs - 如何将 React Web 应用程序部署到 Fiori Launchpad?
- json - 当请求变量是动态的时,无法解析 reqbody json 对象
- python - 从 tkinter 列表框中获取对象