- Python MySQL entry
- Python MySQL create database
- Python MySQL create table
- Python MySQL Insert Table
- Python MySQL Select
- Python MySQL Where
- Python MySQL Order By
- Python MySQL Delete
- Python MySQL drop table
- Python MySQL Update
- Python MySQL Limit
- Python MySQL Join
related suggestion
Python MySQL Join
June 4, 2019
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:}
products
{ id: 154, name: 'Chocolate Heaven' },
{ id: 155, name: 'Tasty Lemons' },
{ id: 156, name: 'Vanilla Dreams' }
The user can use the fav
field and the products id
field, 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)
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"
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"
Note : Hannah and Michael, not like the product, they are excluded from the results.