我该如何简化这个mysql查询?

时间:2013-09-04 17:10:40

标签: php mysql sql

我为每个代理重复了这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);

2 个答案:

答案 0 :(得分:1)

您可以在字段列表

中拥有多个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

正确参数化查询

答案 1 :(得分: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'