数据库
首页 > 数据库> > python – sqlalchemy和double outerjoin

python – sqlalchemy和double outerjoin

作者:互联网

我需要在下面的两个表A和B上进行双外连接才能得到结果
使用SQLAlchemy ORM或SQL表达式.

表B应该是外部连接两次,以便连接两个结果集(由c_id区分),这些结果集用于相同的A记录.外连接用于获取NULL,其中在第一个(c_id = 66)或第二个(c_id = 70)外连接中缺少B结果.

一张桌子:

id
--
1
2
3
4

B表:

id | a_id | c_id
---+------+------
1  |  1   | 66
2  |  2   | 66
3  |  3   | 70
4  |  4   | 66
5  |  4   | 70

查询结果应为:

a_id | b1_id (66) | b2_id (70)
-----+------------+-----------
 1   |  1         |  NULL
 2   |  2         |  NULL
 3   |  NULL      |  3
 4   |  4         |  5

我到了正确的原始SQL查询如下所示:

SELECT 
  A.id AS a_id,
  B_1.id AS b1_id, 
  B_2.id AS b2_id,  
FROM 
  A
LEFT OUTER JOIN   B AS B_1  ON A.id = B_1.a_id AND B_1.c_id = 66
LEFT OUTER JOIN   B AS B_2  ON A.id = B_2.a_id AND B_2.c_id = 70
WHERE
  B_1.id is not NULL or 
  B_2.id is not NULL;

现在,您知道如何在SA ORM或SA SQL表达式中编码吗?

解决方法:

自己找到解决方案:

b1 = aliased(B)
b2 = aliased(B)
q = session.query(A.id, b1.id.label("b1_id"), b1.id.label("b2_id"))
q = q.outerjoin(b1, sqlalchemy.and_(A.id == b1.a_id, b1.c_id == 66))
q = q.outerjoin(b2, sqlalchemy.and_(A.id == b2.a_id, b2.c_id == 70))
q = q.filter(sqlalchemy.or_(b1.id != None, b2.id != None))

标签:python,sqlalchemy,outer-join
来源: https://codeday.me/bug/20190613/1229705.html