Google News
logo
Python Program to RIGHT JOIN
To perform a RIGHT JOIN in Python, we first need to establish a connection to a database and create a table or tables that we want to join.

Then, we can use the `JOIN` keyword along with the `ON` keyword to specify the condition for joining the tables. Finally, we use the `SELECT` statement to retrieve the columns from both tables.

Here's an example program that demonstrates how to perform a RIGHT JOIN using Python and the MySQL database :
Program :
import mysql.connector

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

# create tables to join
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))")
mycursor.execute("CREATE TABLE orders (id INT AUTO_INCREMENT PRIMARY KEY, customer_id INT, amount FLOAT)")

# insert data into the tables
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()

sql = "INSERT INTO orders (customer_id, amount) VALUES (%s, %s)"
val = (1, 50)
mycursor.execute(sql, val)
mydb.commit()

# perform a right join
sql = "SELECT customers.name, orders.amount FROM customers RIGHT JOIN orders ON customers.id = orders.customer_id"
mycursor.execute(sql)
myresult = mycursor.fetchall()

# display the result
for x in myresult:
  print(x)
In this program, we first establish a connection to the MySQL database and create two tables : `customers` and `orders`. We then insert some data into the tables.

To perform a RIGHT JOIN, we use the `RIGHT JOIN` keywords along with the `ON` keyword to specify the condition for joining the tables. In this case, we join the `orders` table with the `customers` table based on the `customer_id` column in the `orders` table and the `id` column in the `customers` table.

We then use the `SELECT` statement to retrieve the `name` column from the `customers` table and the `amount` column from the `orders` table.

Finally, we display the result of the query using a `for` loop.