Google News
logo
Python Program to Combine rows from two or more tables, based on a related column between them
To combine rows from two or more tables, you can use the JOIN clause in SQL. Here's an example Python program that demonstrates how to use the JOIN clause to combine rows from two tables :
Program :
import mysql.connector

# Connect to the database
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="mydatabase"
)

# Create a cursor object to execute SQL queries
mycursor = mydb.cursor()

# SQL query to join two tables
sql = "SELECT customers.name, orders.product_name FROM customers JOIN orders ON customers.id = orders.customer_id"

# Execute the query
mycursor.execute(sql)

# Fetch all the rows
result = mycursor.fetchall()

# Display the result
for row in result:
  print(row)
In the above example, we have two tables `customers` and `orders` with a related column `id` in `customers` table and `customer_id` in `orders` table.

We use the JOIN clause to combine rows from these two tables based on the related column `id` and `customer_id`. The resulting table will have columns `name` from `customers` table and `product_name` from `orders` table.

We then execute the query using the cursor object and fetch all the rows using the `fetchall()` method. Finally, we loop through the rows and display the result.