Python 如何打印左联接的结果
我在python中显示左连接的结果时遇到问题。问题是: 我有两张桌子。一个客户表和一个重量表,用于跟踪每个客户的重量记录 客户表:Python 如何打印左联接的结果,python,mysql,Python,Mysql,我在python中显示左连接的结果时遇到问题。问题是: 我有两张桌子。一个客户表和一个重量表,用于跟踪每个客户的重量记录 客户表: pID Name 01 John 02 Charlotte 权重表: wID pID Weight 01 01 90 02 01 93 03 01 92 04 02 76 05 02 74 当我将左连接存储在python游标中时,我得到了这个结果 pID
pID Name
01 John
02 Charlotte
权重表:
wID pID Weight
01 01 90
02 01 93
03 01 92
04 02 76
05 02 74
当我将左连接存储在python游标中时,我得到了这个结果
pID Name wID Weight
01 John 01 90
01 John 02 93
01 John 03 92
02 John 04 76
02 John 05 74
我的目标是展示:
pID: 01
Name: John
wID: 01 Weight: 90
wID: 02 Weight: 93
wID: 03 Weight: 92
pID: 02
Name: Charlotte
wID: 04 Weight: 76
wID: 05 Weight: 74
现在是Python代码。我有一个Customer类,它存储person ID、Name和一个数组,其中包含为此人注册的所有权重
这是我试图将所有客户及其权重存储在一个名为customers的列表中
customers = []
query = "SELECT * FROM customers LEFT JOIN weights ON customers.idcustomers = weigths.idcustomers"
try:
self.cur = self.connect()
self.cur.execute(query)
queryResults = self.cur.fetchall()
self.desconectar()
except Exception as e:
print(e)
pass
for row in queryResults:
found = False
for cus in customers:
if row[0] == cus.id:
cus.weights.append(Weight(row[0],row[2],row[3]))
found = True
if found == False:
newCustomer = Customer(row[0],row[1])
newCustomer.weights.append(Weight(row[0],row[2],row[3]))
customers.append(newCustomer)
return customers
出于某种原因,我将所有权重添加到每个客户中
customers = []
query = "SELECT * FROM customers LEFT JOIN weights ON customers.idcustomers = weigths.idcustomers"
try:
self.cur = self.connect()
self.cur.execute(query)
queryResults = self.cur.fetchall()
self.desconectar()
except Exception as e:
print(e)
pass
for row in queryResults:
found = False
for cus in customers:
if row[0] == cus.id:
cus.weights.append(Weight(row[0],row[2],row[3]))
found = True
if found == False:
newCustomer = Customer(row[0],row[1])
newCustomer.weights.append(Weight(row[0],row[2],row[3]))
customers.append(newCustomer)
return customers
结果如下所示:
pID: 01
Name: John
wID: 01 Weight: 90
wID: 02 Weight: 93
wID: 03 Weight: 92
wID: 04 Weight: 76
wID: 05 Weight: 74
pID: 02
Name: Charlotte
wID: 01 Weight: 90
wID: 02 Weight: 93
wID: 03 Weight: 92
wID: 04 Weight: 76
wID: 05 Weight: 74
我已经尝试了一段时间来解决这个问题,我真的不知道为什么每个人都在储存每一个重量
这段代码是原始脚本的简化版本,希望我没有弄糟
欢迎任何帮助。。提前谢谢
编辑:查询结果正确,我在翻译SQL行时出错
失败的是python代码。确保在两个表上都加入
pID
我不确定您是如何定义这些类的,但似乎您的查询中的JOIN
条件将pID
与wID
连接起来:
query=“SELECT*FROM customers LEFT JOIN weights ON customers.idcustomers=weights.idweights”
因此,请按原样检查左连接的结果,以确保结果符合预期
然后,进入附加结果的Python
逻辑。但我认为那应该没问题
PS:类Weight
和Peso
之间有什么区别吗?谢谢你的回答jose,你提到的两件事都是我在OP上修正的翻译错误。Peso和Weight是同一类,查询在mysql上按预期工作。我就是不能用python代码对信息进行排序。也许我可以用其他方法来显示这些信息?你试过运行这个简化的脚本吗?虽然有一些效率低下的地方,但您的查询看起来不错,至少for循环的逻辑应该可以工作。这里有太多错误信息,很难提供帮助