August 17, 2024
Join query in sqlalchemy
Suppose we have two tables, Customers and Orders, with the following structures:
Customers Table
- cust_id
- cust_name
- cust_address
- cust_email
Orders Table
- order_id
- cust_id
- order_date
To query these tables using SQL, you could write below mentioned query:
SELECT Customers.*, Orders.order_id, Orders.order_date
FROM Customers
JOIN Orders ON Customers.cust_id = Orders.cust_id
WHERE Customers.cust_id = '23451';
To achieve the same result using SQLAlchemy, you would write:
bond_details = conn.execute(
Customers.join(Orders, Customers.c.cust_id == Orders.c.cust_id)
.select()
.with_only_columns(
Customers.c.cust_id,
Customers.c.cust_name,
Customers.c.cust_address,
Customers.c.cust_email,
Orders.c.order_id,
Orders.c.order_date
)
.where(Customers.c.cust_id == '23451')
)
This query joins the Customers and Orders tables on cust_id, selecting all customer information along with the corresponding order_id and order_date for the customer with cust_id '23451'.