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

时间:2010-05-28 10:10:18

标签: php mysql

伙计们,我需要从表中计算新的私人消息和旧的消息

所以首先想到的是使用mysql_num_rows和简单的事情

  // 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);

但是我如何才能在一个语句和更短的行中计算这两个字段?〜

4 个答案:

答案 0 :(得分:5)

请改用此查询:

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'

这是一个特定于MySQL的版本,读得更干净:

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'

答案 1 :(得分:2)

MySQL会将比较转换为1或0.您可以使用SUM()来添加您尝试计算结果的WHERE子句的部分。

这是(MySQL特定的)较短的替代CASE WHEN示例。

SELECT 
  SUM(pm_new='1' OR pm_unread='1') as new_pms, 
  SUM(pm_new='0' OR pm_unread='0') as old_pms
FROM bb3privmsgs_to
WHERE user_id='$userid'

答案 2 :(得分:1)

在SQL Server中,您可以执行以下操作:

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

我想你可以在mySql中做同样的事情,让我回复你的细节......

答案 3 :(得分:1)

作为其他一些建议的懒惰替代方案:

SELECT SUM(newPMS) AS newPMS,
       SUM(oldPMS) AS oldPMS
  FROM ( SELECT COUNT(author_id) AS newPMS,
                0 AS oldPMS
           FROM bb3privmsgs_to
          WHERE user_id='$user_id'
            AND (pm_new='1' OR pm_unread='1')
         UNION
         SELECT 0 AS newPMS
                COUNT(author_id) AS oldPMS
           FROM bb3privmsgs_to
          WHERE user_id='$user_id'
            AND (pm_new='0' OR pm_unread='0')
       )