dongnan1899 2013-09-04 17:10
浏览 36
已采纳

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

I have these 4 queries repeated 3 times for each agent. Is there anyway to simplify/combine these queries? I don't mind using a while loop for the sums. The only thing that changes are the dates.

$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条回答 默认 最新

  • douju6542 2013-09-04 17:16
    关注

    You can have multiple SUM aggregators in the field list

    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'
    

    Your code is vulnerable to injection. You should use properly parameterized queries with PDO or mysqli

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!