Google News
logo
Python Program to LEFT JOIN
Here's a Python program that demonstrates how to use LEFT JOIN to combine rows from two tables based on a related column :
Program :
import mysql.connector

# Establish a connection 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 select all records from the "customers" table and join the "orders" table using a left join
sql = "SELECT customers.name AS customer_name, orders.product_name AS order_name FROM customers LEFT JOIN orders ON customers.id = orders.customer_id"

# Execute the query
mycursor.execute(sql)

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

# Display the result
for row in result:
  print(row)
In this example, we first establish a connection to the database using the `mysql.connector` module. We then create a cursor object to execute SQL queries.

The SQL query used in this program selects all records from the `customers` table and joins the `orders` table using a left join. The `customers.id` column is used to join the two tables.

We then execute the query using the `mycursor.execute()` method and fetch all the rows returned by the query using the `mycursor.fetchall()` method.

Finally, we loop through the rows and print each row using the `print()` function.