MySQL RIGHT JOIN嵌套子查询

时间:2016-08-15 15:12:12

标签: php mysql join nested

我在" c"上有一个正确的加入以下查询我的子查询

$sqlbsc="SELECT customers.LastName, Sum(IFNULL(scripts.PharmAmount,0)) AS SumPharm, customers.ChemistID, customers.FullName 

   FROM 

   (SELECT scripts.WrittenOff, scripts.PharmAmount, scripts.ChemistID, scripts.ReconcilID, claims.CustomerID FROM scripts 

   INNER JOIN 

   claims ON scripts.ClaimID = claims.ClaimID 

   WHERE 

   (((scripts.WrittenOff)=False) AND ((scripts.ChemistID)='".$_SESSION['chsh']."') AND ((scripts.ReconcilID) IS NULL))) c 

   RIGHT JOIN customers ON c.CustomerID = customers.CustomerID 

   GROUP BY customers.LastName, customers.ChemistID, customers.FullName 

   HAVING ((customers.ChemistID)='".$_SESSION['chsh']."') 

   ORDER BY customers.LastName";

最终以

结束
Customers.FirstName, Customers.LastName and Sum(Scripts.pharmamount) where Scripts.reconcilID IS NULL

但我希望我的所有客户都从我的客户表中显示,只显示为sum = $0.00

我作为子查询在Ms Ms中工作,但上面没有给我任何东西。

我的结果对于我的子查询SQL是正确的。当我使用它时,它可以工作,但我的主要查询不起作用。

任何人都可以提供一些见解吗?

1 个答案:

答案 0 :(得分:1)

修好了!!! 2小时..然后张贴在这里,我固定在1分钟左右 我需要将scripts.pharmamount更改为c.pharmamount,因为它引用子查询而不是实际的表!!

最终查询非常相似:

$sqlbsc="SELECT customers.LastName, Sum(IFNULL(c.PharmAmount,0)) AS SumPharm, customers.ChemistID, customers.FullName

FROM

(SELECT scripts.WrittenOff, scripts.PharmAmount, scripts.ChemistID, scripts.ReconcilID, claims.CustomerID FROM scripts

INNER JOIN

claims ON scripts.ClaimID = claims.ClaimID

WHERE

(((scripts.WrittenOff)=False) AND ((scripts.ChemistID)='".$_SESSION['chsh']."') AND ((scripts.ReconcilID) IS NULL))) c

RIGHT JOIN customers ON c.CustomerID = customers.CustomerID

GROUP BY customers.LastName, customers.ChemistID, customers.FullName

HAVING ((customers.ChemistID)='".$_SESSION['chsh']."')

ORDER BY customers.LastName";