SELECT语句内部联接

时间:2019-03-25 03:51:50

标签: mysql

我正在尝试确定是否可以对现在的三个查询中的一个查询。

 $sql     = "SELECT * 
             FROM joblist WHERE customer = :customer"; // this is a bindParam 

 $sql_val = "SELECT a.customer, SUM(a.value) AS tvalue
             FROM joblist AS a
             INNER JOIN joblist AS b
             ON a.customer = b.customer
             GROUP BY a.customer";

 $sql_bal = "SELECT *
             FROM (SELECT SUM(balance) AS tbalance 
             FROM joblist GROUP BY customer) AS total_balance
             WHERE tbalance = :tbalance";

我使用的表是customer,下面是列。

ID - work_order - customer - description - value - balance - status - notes

我正在使用php PDO和HTMl。

基本上,我具有用于查询公司的搜索功能。显示结果,但我需要“值”和“余额”列的总计。唯一有效的方法是从表中提取数据。我没有获得价值和平衡的总和。

Current code page

1 个答案:

答案 0 :(得分:0)

可能无法很好地理解您的问题,所以我会做出一些猜测:

SELECT
  t1.*,
  t2.tvalue,
  t3.tbalance
FROM
  (SELECT
    *
  FROM
    joblist
  WHERE customer = :customer) t1
  JOIN
    (SELECT
      a.customer,
      SUM(a.value) AS tvalue
    FROM
      joblist AS a
    GROUP BY a.customer) t2
    ON t1.customer = t2.customer
  JOIN
    (SELECT
      b.customer,
      SUM(b.balance) AS tbalance
    FROM
      joblist AS b
    GROUP BY b.customer
    HAVING tbalance = :tbalance) t3
    ON t3.customer = t1.customer;