如何使用&lt; <colname>&gt;组在MySQL中正确吗?</colname>

时间:2013-05-04 11:03:57

标签: mysql sql count

以下是我表格中的数据

| count(*) | system |
|        2 | sys1   |
|        7 | sys2   |
|        6 | sys1   |

我希望输出如下

| count(*) | system |
|        8 | sys1   |
|        7 | sys2   |

我该怎么做?
以下是我正在使用的查询。谁能告诉我这有什么问题?

select * from 

(select count(*),system from tbl1 where creationDate < CURDATE() AND creationDate >= CURDATE() - INTERVAL 1 DAY group by system 

UNION ALL 

select count(*),system from tbl2 where creationDate < CURDATE() AND creationDate >= CURDATE() - INTERVAL 1 DAY group by system) as tbl3 group by system;

1 个答案:

答案 0 :(得分:2)

您需要使用子查询来实现此目的:

试试这个:

SELECT SUM(Total) AS `Count`, system
FROM
(
    SELECT COUNT(*) AS Total, system FROM tbl1 
            WHERE creationDate < CURDATE() 
              AND creationDate >= CURDATE() - INTERVAL 1 DAY GROUP BY system
    UNION ALL
     SELECT COUNT(*) AS Total, system FROM tbl2 
            WHERE creationDate < CURDATE() 
              AND creationDate >= CURDATE() - INTERVAL 1 DAY GROUP BY system
) A
GROUP BY system

输出:

| COUNT | system |
|     8 | sys1   |
|     7 | sys2   |