如何计算&同一查询中同一个表的其他列?

时间:2015-01-27 18:01:38

标签: mysql

我正在尝试下面的MySql查询 -

SELECT count(*), bug_id, 
       bug_status, 
       resolution, 
       short_desc, 
       DATE_FORMAT(deadline, "%m/%d/%Y")AS deadline
FROM   bugs 
WHERE  ( bug_status IN ( 'RESOLVED', 'VERIFIED', 'INTEST' ) 
         AND deadline BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY) 
       ) 
        OR ( bug_status IN ( 'RESOLVED', 'VERIFIED', 'INTEST' ) 
             AND deadline BETWEEN DATE_SUB(CURDATE(), INTERVAL 30 DAY) AND 
                                  CURDATE() )        
       ORDER BY deadline ASC

但它返回的结果只有一列而不是所有96个条目..

enter image description here

什么是更好的主意,以便我先得到计数然后得到所有结果?

2 个答案:

答案 0 :(得分:1)

COUNT()子句中存在SELECT(或任何其他聚合函数)会将查询转换为聚合查询。如果没有GROUP BY子句,聚合查询必须只返回一行。

如果必须在每一行中返回count项,则必须在连接的单行子查询中获取它。像这样的东西可以解决问题。

SELECT b.cnt, a.*
  FROM table a
  JOIN (SELECT COUNT(*) cnt FROM table) b ON 1=1

但是对于你有的大问题,你必须在我提到table的地方重复两次。

答案 1 :(得分:1)

如果你想在每一行中完整计数,那么在MySQL中有点难看。你基本上有两个选择:

  1. 执行两个单独的查询并将结果放回调用代码
  2. 在MySQL中有效地执行两个单独的查询,并将结果放在MySQL中
  3. 以下是如何将它们放在MySQL中 - 注意你的WHERE逻辑必须如何重复:

    SELECT
      CountOnly.RowCount,
      bug_status,
      resolution,
      short_desc,
      DATE_FORMAT(deadline, '%m/%d/%Y') AS deadline
    FROM bugs
    INNER JOIN (
      SELECT COUNT(*) AS RowCount
      FROM bugs
      WHERE 
       ( bug_status IN ( 'RESOLVED', 'VERIFIED', 'INTEST' ) 
         AND deadline BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY) 
       ) 
       OR ( bug_status IN ( 'RESOLVED', 'VERIFIED', 'INTEST' ) 
            AND deadline BETWEEN DATE_SUB(CURDATE(), INTERVAL 30 DAY) AND CURDATE() )
    ) CountOnly ON 1 = 1
    WHERE
     ( bug_status IN ( 'RESOLVED', 'VERIFIED', 'INTEST' ) 
       AND deadline BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY) 
     ) 
     OR ( bug_status IN ( 'RESOLVED', 'VERIFIED', 'INTEST' ) 
          AND deadline BETWEEN DATE_SUB(CURDATE(), INTERVAL 30 DAY) AND CURDATE() )