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)