如何查询2个表

时间:2013-07-07 13:40:40

标签: php join

我需要在tblgl (tblgl.SUM(InMonthActual))中汇总选择成本中心(tblgl.CostCentreCode)的交易,其中满足以下条件:

  1. tblgl.PeriodNumber = 2
  2. tblgl.CostCentreCode = tblcostcentrehierarchy.CostCentreCode WHERE tblcostcentrehierarchy.Level7 = "RWK312 CORPORATE"
  3. tblgl.CostCentreCode = tblcostcentreallocations.CostCentreCode WHERE tblcostcentreallocations.Username = "jonest"
  4. 目前我正在运行3个单独的查询来创建一个在下一个查询中使用的数组。

    有没有办法在一个方面(可能使用 JOIN )?

2 个答案:

答案 0 :(得分:1)

我希望此查询能够获取您想要的数据。检查并告诉我它是否适合您。

   SELECT SUM(tb1.`InMonthActual`) 
   FROM `tblgl` as tb1 
   JOIN `tblcostcentrehierarchy` as tb2 ON tb1.`CostCetntreCode` = tb2.`CostCentreCode`
   JOIN `tblcostcentreallocations` as tb3 ON tb1.`CostCetntreCode` = tb3.`CostCentreCode`
   WHERE tb1.`PeriodNumber` = '2' AND tb2.`Level17` = "RWK312 CORPORATE" AND tb3.`Username` = "jonest"

答案 1 :(得分:0)

试一试

SELECT SUM(tblgl.InMonthActual) FROM tblgl
INNER JOIN tblcostcentrehierarchy ON (tblgl.CostCentreCode = tblcostcentrehierarchy.CostCentreCode AND tblgl.PeriodNumber = 2)
INNER JOIN tblcostcentreallocations ON  (tblgl.CostCentreCode = tblcostcentreallocations.CostCentreCode)
WHERE tblcostcentreallocations.Username = "jonest" AND tblcostcentrehierarchy.Level7 = "RWK312 CORPORATE"
GROUP BY tblgl.InMonthActual

希望它运作良好