SQL查询返回重复的结果

时间:2010-02-23 05:03:36

标签: sql mysql duplicates

我一直在研究这个问题已经有一段时间了,我想我已经把它放在了我想要的地方,但显然没有。

数据库中有两条记录(订单)。查询应该返回两个不同的行,而是返回两个具有完全相同值的行。我认为这可能与我正在使用的GROUP BY或派生表有关,但我的眼睛很累,没有看到问题。你们有人可以帮忙吗?提前谢谢。

SELECT orders.billerID, 
    orders.invoiceDate, 
    orders.txnID, 
    orders.bName, 
    orders.bStreet1, 
    orders.bStreet2, 
    orders.bCity, 
    orders.bState, 
    orders.bZip, 
    orders.bCountry, 
    orders.sName, 
    orders.sStreet1, 
    orders.sStreet2, 
    orders.sCity, 
    orders.sState, 
    orders.sZip, 
    orders.sCountry, 
    orders.paymentType, 
    orders.invoiceNotes, 
    orders.pFee, 
    orders.shipping, 
    orders.tax, 
    orders.reasonCode, 
    orders.txnType, 
    orders.customerID, 
    customers.firstName AS firstName, 
    customers.lastName AS lastName, 
    customers.businessName AS businessName, 
    orderStatus.statusName AS orderStatus, 
    IFNULL(orderItems.itemTotal, 0.00) + orders.shipping + orders.tax AS orderTotal, 
    IFNULL(orderItems.itemTotal, 0.00) + orders.shipping + orders.tax - IFNULL(payments.totalPayments, 0.00) AS orderBalance 
FROM orders 
LEFT JOIN customers ON orders.customerID = customers.id 
LEFT JOIN orderStatus ON orders.orderStatus = orderStatus.id
LEFT JOIN 
    ( 
      SELECT orderItems.orderID, SUM(orderItems.itemPrice * orderItems.itemQuantity) as itemTotal
      FROM orderItems
      GROUP BY orderItems.orderID
    ) orderItems ON orderItems.orderID = orders.id 
LEFT JOIN 
    ( 
      SELECT payments.orderID, SUM(payments.amount) as totalPayments
      FROM payments
      GROUP BY payments.orderID
    ) payments ON payments.orderID = orders.id

2 个答案:

答案 0 :(得分:3)

通常,当您加入许多表并最终得到重复行时,这是因为您没有看到整个图片。如果您要执行“select *”查看查询中包含的所有列(而不是返回列的子集)并比较结果行,您会发现在某个地方有一个包含不同数据的列

答案 1 :(得分:2)

当我遇到这个问题时,我开始一次评论一个连接(和相关的选定列),直到我发现导致问题的违规连接。