获取连接查询中的列的总和

时间:2016-09-06 16:15:43

标签: php mysql sql

我有查询...

  $productInfo = "SELECT list.* , production.*, Sum(production.units) AS totalQty
      FROM  production
      LEFT JOIN list
      ON list.id = production.com_id
      WHERE id = '$productID'
      AND production.userid = $userID";

由于某种原因,这只返回1行和总和。该表有2行,它们都应该返回。

如果我删除Sum(production.units)AS totalQty,则返回2行,但我将无法检索总和。

最好的方法是什么? 感谢

2 个答案:

答案 0 :(得分:0)

您错过了GROUP BY

SELECT l.*, Sum(p.units) AS totalQty
FROM  production p LEFT JOIN
      list l
      ON l.id = p.com_id
WHERE l.id = '$productID' AND p.userid = $userID
GROUP BY l.id;

实际上,left join按照你拥有的顺序没有意义。你可能打算:

SELECT l.*, Sum(p.units) AS totalQty
FROM  list l LEFT JOIN
      production p 
      ON l.id = p.com_id AND p.userid = $userID
WHERE l.id = '$productID' AND 
GROUP BY l.id;

这将为每个列表提供该用户的生产总和。

答案 1 :(得分:0)

存储函数是一种返回单个值的特殊存储程序。您可以使用存储函数来封装可在SQL语句或存储程序中重用的公共公式或业务规则。

    DELIMITER $$

CREATE FUNCTION mysum(p_creditLimit double,product_id Integer,user_id Interger) RETURNS VARCHAR(10)
    DETERMINISTIC
BEGIN
    DECLARE lvl varchar(10);

  DECLARE select_var VARCHAR(500);
  SET select_var = (SELECT list.* , production.*, Sum(production.units) AS totalQty
      FROM  production
      LEFT JOIN list
      ON list.id = production.com_id
      WHERE id = product_id
      AND production.userid = user_id limit 1);
  RETURN select_var;
END

并简单地调用您的SQL查询

 $productInfo = "SELECT list.* , production.*, mysum(production.units,".$productID.",".$userID.") AS totalQty
      FROM  production
      LEFT JOIN list
      ON list.id = production.com_id
      WHERE id = '".$productID."'
      AND production.userid = $userID";

现在$ productInfo返回所有行。

  

来源http://www.mysqltutorial.org/mysql-stored-function/