我有两张桌子;发票和发票项目。
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
我真的很抱歉,我知道这真的解释得很糟糕,但我无法以任何其他方式解释它,一直在寻找年龄但无法找到解决方案。希望有人可以提供帮助。谢谢