Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何简化这个mysql查询?_Php_Mysql_Sql - Fatal编程技术网

Php 如何简化这个mysql查询?

Php 如何简化这个mysql查询?,php,mysql,sql,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("SEL

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

字段列表中可以有多个
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使用正确的参数化查询。您可以在字段列表中有多个
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中使用正确的参数化查询这类查询对您有帮助吗

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'

这类查询对您有帮助吗

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'

它不一定是易受攻击的–这取决于如何在本节上面处理这些变量。@RichBradshaw,这是不真实的;查询本身具有漏洞。日期字段设置在此查询之前。不是基于用户的。至于mysqli,我目前正在更新我的整个系统。它都是硬编码的,所以需要一些时间。它不一定容易受到攻击——这取决于在本节上面如何处理这些变量。@RichBradshaw,这是不正确的;查询本身具有漏洞。日期字段设置在此查询之前。不是基于用户的。至于mysqli,我目前正在更新我的整个系统。这都是硬编码的,所以需要一些时间。