I have the two following tables.
Users Table
id | name | |
---|---|---|
32 | Hello | e@mail.com |
23 | World | p@mail.com |
Sales Table
id | SellerId | CustomerId | Amount |
---|---|---|---|
4 | 32 | 23 | 25 |
I want to join the tables in the following way to get this result. Here I want to only get the entries where customer id is equal to 23.
Id | SellerId | SellerName | SellerEmail | Amount |
---|---|---|---|---|
4 | 32 | Hello. | e@mail.com | 25. |
And also do another join this way. Here I want to only get the entries where seller id is equal to 32.
id | CustomerId | CustomerName | CustomerEmail | Amount |
---|---|---|---|---|
4 | 23 | World | p@mail.com | 25. |
My code for both the tables is
JavaScript
x
15
15
1
class Users(Base):
2
__tablename__ = "users"
3
4
id = Column(Integer, primary_key=True, index=True)
5
name = Column(String)
6
email = Column(String, unique=True, index=True, nullable=False)
7
8
class Sales(Base):
9
__tablename__="sales"
10
11
id = Column(Integer, primary_key=True, index=True)
12
seller_id = Column(Integer, index=True)
13
customer_id = Column(Integer, index=True)
14
amount = Column(Integer, index=True)
15
I was able to achieve this using raw SQL with the following
JavaScript
1
5
1
SELECT (sales.id), name as SellerName, email as SellerEmail, Amount
2
FROM sales
3
LEFT JOIN user ON sales.SellerId = user.id
4
WHERE CustomerId = 23
5
Please help with doing the same using SqlAlchemy Session.
Advertisement
Answer
JavaScript
1
12
12
1
query = (
2
session.query(
3
Sales.id,
4
Users.name.label('SellerName'),
5
Users.email.label('SellerEmail'),
6
Sales.amount
7
)
8
.select_from(Sales)
9
.outerjoin(Users, Users.id == Sales.seller_id)
10
.filter(Sales.customer_id == 23)
11
)
12