如何打印左联接的结果

2024-04-26 10:28:02 发布

您现在位置:Python中文网/ 问答频道 /正文

在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    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类,它存储personid、Name和一个数组,其中包含为该person注册的所有权重。你知道吗

因此,这是我试图将所有客户及其权重存储在一个名为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代码。你知道吗


Tags: 代码nameself客户johnpidrow权重
1条回答
网友
1楼 · 发布于 2024-04-26 10:28:02

确保在两个表上都加入pID。你知道吗

我不确定您是如何定义这些类的,但似乎您的query上的JOIN条件将pIDwID连接起来:

query = "SELECT * FROM customers LEFT JOIN weights ON customers.idcustomers = weighs.idweights"

因此,检查LEFT JOIN的结果,确保结果如您所期望的那样。你知道吗

然后,进入附加结果的Python逻辑。但我觉得应该没问题。你知道吗

PS:类WeightPeso之间有什么区别吗?你知道吗

相关问题 更多 >