mysql sum()两个连接表,乘以结果

时间:2013-09-10 00:38:15

标签: mysql join sum

我有两张桌子;发票和发票invoiceitems。
invoiceitems包含每张发票上的项目

例如:

invoices
----------------------------------
| id  |status| net | tax | total |
----------------------------------
| 72  |paid  | 100 | 120 |  220  |
| 73  |unpaid| 50  | 5   |  55   |
| 74  |paid  | 400 | 45  |  445  |
| 75  |paid  | 250 | 67  |  317  |


invoiceitems
-------------------------------
| invoiceid |itemdescription |
-------------------------------
| 72        | apples         |
| 72        | pears          |
| 72        | oranges        |
| 73        | lemons         |
| 73        | oranges        |

如您所见,在示例中,发票编号72有3个项目

我想搜索某些东西的发票,并显示某些字段的数量。

但我的问题是和值似乎乘以第二个表中的字段数。

$sql = "SELECT COUNT(DISTINCT invoices.id) AS num, 
SUM(CASE invoices.status WHEN 'Paid' THEN 1 ELSE 0 END) AS numpaid, 
SUM(CASE invoices.status WHEN 'Paid' THEN invoices.total ELSE 0 END) AS sumtotal,
FROM invoices 
LEFT JOIN invoiceitems ON invoices.id=invoiceitems.invoiceid
WHERE invoices.id LIKE :invoiceid 
AND IFNULL(opcinvoiceitems.itemdescription, '')  LIKE :itemdescription
AND invoices.net LIKE :net 
AND invoices.tax LIKE :tax 
AND invoices.total LIKE :total
AND ......" 

因此使用上述内容,发票72的总数将乘以3

我真的很抱歉,我知道这真的很难解释,但我无法用其他任何方式解释,一直在寻找年龄,但无法找到解决方案。希望有人能提供帮助。感谢

2 个答案:

答案 0 :(得分:0)

进行连接时,会生成通过匹配原始表中的记录而创建的记录。因此,您将拥有发票#72的3条记录,每条记录通过将#72的单个发票记录与#72的每个发票项目进行匹配来创建。每个组合记录将具有相同的总数(在这种情况下为220),因此总和将是该总和的3倍。

听起来你只想要总计,然后;您可以直接使用总计,或者您可以将您的总和除以计数(您似乎也在计算)。

答案 1 :(得分:0)

实现目标的一种方法是在加入前预先聚合invoiceItems表:

SELECT COUNT(i.id) AS num, 
       SUM(CASE i.status WHEN 'Paid' THEN 1 ELSE 0 END) AS numpaid, 
       SUM(CASE i.status WHEN 'Paid' THEN i.total ELSE 0 END) AS sumtotal,
FROM invoices  i LEFT JOIN
     (select ii.invoiceid, sum(. . .) as . . .
      from invoiceitems ii
      where IFNULL(ii.itemdescription, '')  LIKE :itemdescription AND
      group by ii.invoiceid
     ) ii
     ON i.id = ii.invoiceid
WHERE i.id LIKE :invoiceid AND
      i.net LIKE :net  AND
      i.tax LIKE :tax AND
      i.total LIKE :total AND .....

您的查询实际上并未在invoiceitems子句中使用from,因此很难提供更详细的示例。