我有两张不相关的表格:
contribution(id,amount, create_at, user_id)
solicitude(id, amount, create_at, status_id, type_id, user_id)
我需要从用户中减去贡献金额和关注度的总和,但结果不能是负数。
我该怎么做?功能还是查询?
我试过这个问题:
SELECT sum(contribution.amount)
- (SELECT sum(solicitude.amount)
FROM solicitude
WHERE user_id = 1 AND status_id = 1) as total
FROM contribution
WHERE contribution.user_id = 1
答案 0 :(得分:2)
您可以添加外部查询以检查总值:
SELECT CASE WHEN total > 0 THEN total ELSE 0 END AS total
FROM (
SELECT
sum(contribution.amount) - (SELECT sum(solicitude.amount)
FROM solicitude
WHERE user_id = 1 AND status_id = 1) as total
FROM contribution
WHERE
contribution .user_id = 1
) alias;
这个解决方案没问题,但我建议采用另一种方法。检查此查询的工作原理:
with contribution as (
select user_id, sum(amount) as amount from contribution
group by 1),
solicitude as (
select user_id, sum(amount) as amount from solicitude
where status_id = 1
group by 1)
select
c.user_id, c.amount as contribution, s.amount as solitude,
case when c.amount > s.amount then c.amount - s.amount else 0 end as total
from contribution c
join solicitude s on c.user_id = s.user_id;
我出于好奇心做了一个简单的测试,在这个设置上:
create table public.solicitude (
id integer,
amount numeric,
create_at timestamp without time zone,
status_id integer,
type_id integer,
user_id integer
);
create table public.contribution (
id integer,
amount numeric,
create_at timestamp without time zone,
user_id integer
);
insert into contribution (user_id, amount)
select (random()* 50)::int, (random()* 100)::int
from generate_series(1, 4000000);
insert into solicitude (user_id, amount, status_id)
select (random()* 50)::int, (random()* 100)::int, 1
from generate_series(1, 4000000);
结果(msecs):
Erwin's solution with greatest(): 922, 905, 922, 904, 904, 904, 905, 912, 905, 922
My solution with an outer query: 796, 795, 814, 814, 815, 795, 815, 796, 815, 796
答案 1 :(得分:0)
我将您的评论but that result can't to be negative
解释为要求返回0而不是否定结果。简单的解决方案是GREATEST()
:
SELECT GREATEST(sum(amount)
- (SELECT sum(amount)
FROM solicitude
WHERE status_id = 1
AND user_id = 1), 0) AS total
FROM contribution
WHERE user_id = 1;
否则,我保留了原始查询,这很好。
对于可能导致无法返回行的其他情况,我将替换为两个子选择。但是使用聚合函数保证结果行,即使根本找不到给定的user_id
。比较:
如果减法的结果为NULL
(因为没有找到行或总和为NULL
),GREATEST()
也将返回0
。
答案 2 :(得分:-1)
你必须加入表格
foreach($result->GetWebOccurrencesResult->OccuList->TOccu as $occurrence) {
编辑:我忘了别名