返回组中的所有行

时间:2015-03-19 23:09:38

标签: php mysql group-by sum

有没有办法获取组中使用的所有行?

正如您所料,以下查询仅返回每custref行一行。但如果totalamount是> 0,我希望它返回组中的所有行。否则没有。

$sql = "SELECT
    debtors.custref,
    debtors.amount,
    users.bnkSort,
    users.bnkAccNum,
    users.bnkAccName,
    SUM(debtors.amount) AS totalamount
    FROM debtors
    LEFT JOIN users ON debtors.custref=users.custref
    WHERE
    users.bank = 'Yes'
    GROUP BY debtors.custref
";

1 个答案:

答案 0 :(得分:1)

您的查询包含多个由group by无效的列 - 这些列在组中的行中不相同。此外,where子句正在撤消left join。所以,这基本上是你的查询:

SELECT d.custref, SUM(d.amount) AS totalamount
FROM debtors d JOIN 
     users u
     ON d.custref = u.custref
WHERE u.bank = 'Yes'
GROUP BY d.custref;

要获取所有字段,可以将其用作子查询:

SELECT d.*, u.*
FROM (SELECT d.custref, SUM(d.amount) AS totalamount
      FROM debtors d JOIN 
           users u
           ON d.custref = u.custref
      WHERE u.bank = 'Yes'
      GROUP BY d.custref
      HAVING totalamount > 0
     ) dc JOIN
     debtors d
     ON dc.custref = d.custref JOIN
     users u
WHERE u.bank = 'Yes';

 ON dc.custref = u.custref