这给了我一个使用外部资金的用户列表。
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
的内容时,我会得到一个空集。我知道有数千名用户没有使用外部资金。
答案 0 :(得分:2)
假设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;
我还为表使用了表别名。我认为这样可以更容易阅读。
答案 1 :(得分:0)
由于HAVING子句不起作用,听起来那些没有使用外部资金的用户在table_deposit中没有行。如果是这种情况,您的查询应该是:
SELECT
table_user.user as user,
0 as TotalExternalDeposits,
payby,
pro_id
FROM table_user
WHERE user NOT IN (
SELECT user
FROM table_deposit
)
答案 2 :(得分:0)
如果它是一个或者您只需要相反的查询集,只需反转标准:
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'
OR table_deposit.batch LIKE '%adj%'
OR table_deposit.batch LIKE 'Xmas%'
OR table_deposit.batch LIKE 'X-mas%'
group by table_user.user
order by table_user.user
答案 3 :(得分:0)
我认为HAVING
可以解决问题,但可能是因为您似乎忘记在payby
条款中添加pro_id
和GROUP BY
是因为你尝试了别名。
SELECT
table_user.user as user,
sum(table_deposit.amount) as TotalExternalDeposits,payby,table_deposit.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,payby,table_deposit.pro_id
HAVING sum(table_deposit.amount) = 0
ORDER BY table_user.user