dongmou3615 2010-05-28 10:10
浏览 81
已采纳

在一个查询中计算两个字段的问题

guys i need to count new private messages and old one from a table

so first thing come to mind is using mysql_num_rows and easy thing to do

  // check new pms
  $user_id  = $userinfo['user_id'];
  $sql = "SELECT author_id  FROM bb3privmsgs_to WHERE user_id='$user_id' AND (pm_new='1' OR  pm_unread='1')";
  $result = $db->sql_query($sql) ;
  $new_pms = $db->sql_numrows($result);
  $db->sql_freeresult($result);

  // check old pms
  $sql = "SELECT author_id  FROM bb3privmsgs_to WHERE user_id='$user_id' AND (pm_new='0' OR  pm_unread='0')";
  $result = $db->sql_query($sql) ;
  $old_pms = $db->sql_numrows($result);
  $db->sql_freeresult($result);

but how can i count these two fields just in one statement and shorter lines ?~

  • 写回答

4条回答 默认 最新

  • dongzha0149 2010-05-28 10:17
    关注

    Use this query instead:

    SELECT SUM(CASE WHEN pm_new = '1' OR pm_unread = '1' THEN 1 ELSE 0 END) AS new_pms,
           SUM(CASE WHEN pm_new = '0' OR pm_unread = '0' THEN 1 ELSE 0 END) AS old_pms
      FROM bb3privmsgs_to
     WHERE user_id='$user_id'
    

    Here's a MySQL-specific version that reads more cleanly:

    SELECT COUNT(IF(pm_new = '1' OR pm_unread = '1', 1, NULL)) AS new_pms,
           COUNT(IF(pm_new = '0' OR pm_unread = '0', 1, NULL)) AS old_pms
      FROM bb3privmsgs_to
     WHERE user_id='$user_id'
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog