Showing posts with label MySQL_left_join. Show all posts
Showing posts with label MySQL_left_join. Show all posts

Jan 26, 2019

Python MySQL

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="password",
  database="myproject"
)

my_cursor = mydb.cursor()

sql = "SELECT user.name, product.name FROM user JOIN product ON user.product_id = product.id"

my_cursor.execute(sql)

results = my_cursor.fetchall()

for each in results:
  print each

MySQL Joins

  #INNER JOIN - this gives common elements from user & product
  SELECT user.name, product.name 
  FROM user INNER JOIN product ON user.product_id = product.id
  
  #LEFT JOIN - this gives all user & matching product
  SELECT user.name, product.name 
  FROM user LEFT JOIN product ON user.product_id = product.id
  
  #RIGHT JOIN - this gives all product with user
  SELECT   user.name, product.name 
  FROM user RIGHT JOIN product ON user.product_id = product.id