Python MySQL Join

Python MySQL Tutorial

related suggestion

Python MySQL Join

June 4, 2019

 Feedback

Connecting two or more tables

JOIN statement may be used, according to the related field between multiple tables, the combination of these tables into one table.

Suppose there is a "users" table and a "products" table:

users

{ id: 1, name: 'John', fav: 154},
{ id: 2, name: 'Peter', fav: 154},
{ id: 3, name: 'Amy', fav: 155},
{ id: 4, name: 'Hannah', fav:},
{ id: 5, name: 'Michael', fav:}

copy

products

{ id: 154, name: 'Chocolate Heaven' },
{ id: 155, name: 'Tasty Lemons' },
{ id: 156, name: 'Vanilla Dreams' }

copy

The user can use the favfield and the products idfield, combines the two tables.

Examples

Connected users table and products table, view the user's favorite product:

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="你的用户名",
  passwd="你的密码",
  database="mydatabase"
)

mycursor = mydb.cursor()

sql = "SELECT \
  users.name AS user, \
  products.name AS favorite \
  FROM users \
  INNER JOIN products ON users.fav = products.id"

mycursor.execute(sql)

myresult = mycursor.fetchall()

for x in myresult:
  print(x)

copy

Note : JOIN and INNER JOIN equivalent, they will give you the same results.

Left connection

In the above example, Hannah and Michael are excluded from the result, because the matching records INNER JOIN display only.

If you want to display all users, even if they do not like the product, you can use LEFT JOIN statement:

Examples

Queries all users and their favorite products:

sql = "SELECT \
  users.name AS user, \
  products.name AS favorite \
  FROM users \
  LEFT JOIN products ON users.fav = products.id"

copy

The right connection

If you want to return all products, and users like them, you can use RIGHT JOIN statement:

Examples

Like all product inquiries and their users:

sql = "SELECT \
  users.name AS user, \
  products.name AS favorite \
  FROM users \
  RIGHT JOIN products ON users.fav = products.id"

copy

Note : Hannah and Michael, not like the product, they are excluded from the results.


Doc navigation

← Python MySQL Limit

Guess you like

Origin blog.csdn.net/matthewwu/article/details/93381161