我有3个表(产品,bill_Details和账单),我想在bill_details表中检索每个产品的数量,下面的查询只是给我在bill_details表中的产品"只是",和如果bill_details为空,则无法检索!
这是我的疑问:
select p.prod_Id,p.prod_Name,
sum(b.de_Quantity+b.de_Bonus) - sum(bbb.de_Quantity+bbb.de_Bonus),
p.prod_Cost,p.prod_ExpDate,p.prod_BonusInfo,p.prod_Note
from
(((products p left JOIN bill_Details b on p.prod_Id=b.prod_Id)
left JOIN bill_Details bbb on p.prod_Id=bbb.prod_Id )
left JOIN bills a on b.bill_Id = a.bill_Id)
left JOIN bills aaa on bbb.bill_Id = aaa.bill_Id
where
a.cus_Sup=1 and aaa.cus_Sup=0 and a.archived=0 and aaa.archived=0
group by p.prod_Id,p.prod_Name,p.prod_Cost,p.prod_ExpDate,
p.prod_BonusInfo,p.prod_Note order by p.prod_Name asc;
答案 0 :(得分:0)
您的WHERE
子句正在检查已连接的表。通过这样做,您实际上删除了左连接中不匹配的行。可能不是你想要的。
相反,你想要的可能是在join子句本身中移动这些条件,如下所示:
select p.prod_Id,p.prod_Name,
sum(b.de_Quantity+b.de_Bonus) - sum(bbb.de_Quantity+bbb.de_Bonus),
p.prod_Cost,p.prod_ExpDate,p.prod_BonusInfo,p.prod_Note
from
(((products p left JOIN bill_Details b on p.prod_Id=b.prod_Id)
left JOIN bill_Details bbb on p.prod_Id=bbb.prod_Id )
left JOIN bills a on b.bill_Id = a.bill_Id and a.cus_Sup=1 and a.archived=0)
left JOIN bills aaa on bbb.bill_Id = aaa.bill_Id and aaa.cus_Sup=0 and aaa.archived=0
group by p.prod_Id,p.prod_Name,p.prod_Cost,p.prod_ExpDate,
p.prod_BonusInfo,p.prod_Note order by p.prod_Name asc;