这给了我一个使用外部资金的用户列表。

SELECT
  table_user.user as user,
  sum(table_deposit.amount) as TotalExternalDeposits,payby,pro_id
FROM table_deposit inner join table_user on table_deposit.user = table_user.user
WHERE  table_deposit.pro_id <>  'Cash A/C'
AND  table_deposit.batch NOT LIKE  '%adj%'
AND table_deposit.batch NOT LIKE  'Xmas%'
AND table_deposit.batch NOT LIKE  'X-mas%'
group by table_user.user
order by table_user.user

我的问题是现在我需要一个没有使用外部资金的用户列表(TotalExternalDeposits = 0)。我迷路了。
当我尝试添加类似:HAVING TotalExternalDeposits = 0的内容时,会得到一个空集。我知道有成千上万的用户没有使用外部资金。

最佳答案

假设join没有过滤掉您正在寻找的任何用户,您可以使用not

SELECT table_user.user as user, sum(table_deposit.amount) as TotalExternalDeposits,payby,pro_id
FROM table_deposit inner join
     table_user
    on table_deposit.user = table_user.user
WHERE not (`table_deposit`.pro_id <>  'Cash A/C' AND
           `table_deposit`.batch NOT LIKE  '%adj%' AND
           table_deposit.batch NOT LIKE  'Xmas%' AND
           table_deposit.batch NOT LIKE  'X-mas%'
          )
group by `table_user`.user
order by `table_user`.user

然而,这会让拥有非“外部资金”账户的用户受益。也就是说,上面得到的用户至少有一个非外部资金帐户。您可能需要确保没有账户是外部资金(而不是任何)。在这种情况下,您希望将条件移到having子句中,在该子句中可以计算匹配的行,并确保值为0:
SELECT tu.user as user, sum(td.amount) as TotalExternalDeposits, payby, pro_id
FROM table_user tu left outer join
     table_deposit td
     on td.user = tu.user
group by tu.user
having sum((td.pro_id <>  'Cash A/C' AND
            td.batch NOT LIKE  '%adj%' AND
            td.batch NOT LIKE  'Xmas%' AND
            td.batch NOT LIKE  'X-mas%'
           ) or td.user is null
          ) = 0
order by tu.user;

我还为表使用了表别名。我觉得这样更容易阅读。

关于mysql - SELECT复杂查询的相反一组行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17903012/

10-13 05:48