Python MySQL Join
Python基础 2022-06-06 12:58:34小码哥的IT人生shichen
Python MySQL Join
组合两张或更多表
您可以使用 JOIN 语句,根据它们之间的相关列组合两个或多个表中的行。
假设您有 "users" 表和 "products" 表:
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' }
可以使用 users 的 fav
字段和 products 的 id
字段来组合这两个表。
示例代码:
组合用户和产品,查看用户最喜欢的产品名称:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
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)
完整实例:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
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)
注释:您可以使用 JOIN 而不是 INNER JOIN。您都会得到相同的结果。
LEFT JOIN
在上例中,Hannah 和 Michael 被排除在结果之外,这是因为 INNER JOIN 只显示匹配的记录。
如果希望显示所有用户,即使他们没有喜欢的产品,请使用 LEFT JOIN 语句:
示例代码:
选择所有用户及其喜爱的产品:
sql = "SELECT \
users.name AS user, \
products.name AS favorite \
FROM users \
LEFT JOIN products ON users.fav = products.id"
完整实例:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "SELECT \
users.name AS user, \
products.name AS favorite \
FROM users \
LEFT JOIN products ON users.fav = products.id"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
RIGHT JOIN
如果您想要返回所有产品以及喜欢它们的用户,即使没有用户喜欢这些产品,请使用 RIGHT JOIN 语句:
示例代码:
选择所有产品以及喜欢它们的用户:
sql = "SELECT \
users.name AS user, \
products.name AS favorite \
FROM users \
RIGHT JOIN products ON users.fav = products.id"
完整实例:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "SELECT \
users.name AS user, \
products.name AS favorite \
FROM users \
RIGHT JOIN products ON users.fav = products.id"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
注释:不对任何产品感兴趣的 Hannah 和 Michael 不包括在结果中。