1

我为每个代理重复了这 4 个查询 3 次。有没有办法简化/组合这些查询?我不介意使用 while 循环来计算总和。唯一改变的是日期。

$john_week_total  = mysql_result(mysql_query("SELECT SUM(tp) FROM info WHERE type='life' AND date >= '$monday' AND rvp ='john smith'"),0);
$john_month_total = mysql_result(mysql_query("SELECT SUM(tp) FROM info WHERE type='life' AND date >= '$this_month' AND rvp ='john smith'"),0);
$john_year_total  = mysql_result(mysql_query("SELECT SUM(tp) FROM info WHERE type='life' AND date >= '$this_year' AND rvp ='john smith'"),0);
$john_total       = mysql_result(mysql_query("SELECT SUM(tp) FROM info WHERE type='life' AND rvp ='john smith'"),0);
4

2 回答 2

0

您可以在字段列表中有多个SUM聚合器

SELECT
    SUM(IF(date >= '$monday' AND rvp = 'john smith'), tp, 0) AS john_week_total
    SUM(IF(date >= '$this_month' AND rvp = 'john smith'), tp, 0) AS john_month_totalo
    -- etc.
FROM
    info
WHERE
    type = 'life'

您的代码容易被注入。您应该使用带有 PDO 或 mysqli 的正确参数化查询

于 2013-09-04T17:16:53.747 回答
0

这种查询对您有帮助吗?

select
   sum(case when date >= '$monday' then tp else 0 end) as weektotal,
   sum(case when date >= '$this_month' then tp else 0 end) as monthtotal,
   sum(case when date >= '$this_year' then tp else 0 end) as yeartotal,
   sum(tp) as alltotal
from info
where type = 'life'
and rvp = 'john smith'
于 2013-09-04T17:17:11.020 回答