mysql中的COUNT和GROUP BY问题

时间:2013-03-11 12:42:26

标签: mysql sql count

我有四张桌子,这是

CREATE TABLE `table1` (
`id` int(22) NOT NULL auto_increment,
`createdDate` date NOT NULL,
`created_by` int(44) NOT NULL,
 PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=21 ;

CREATE TABLE `table2` (
`id` int(99) NOT NULL auto_increment,
`CompanyName` varchar(99) NOT NULL,
`createdDate` date NOT NULL,
 `created_by` int(44) NOT NULL,
 PRIMARY KEY  (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=19076 ;

类似于table3和table4

我想显示这样的结果

Date          | userid    |Total_of_table1  | Total_of_table2  |Total_of_table3

2013-03-11    | 1         |20               |23                |24

这个查询将如何? 简单就是用户在每个表中总计的日期(天)

1 个答案:

答案 0 :(得分:1)

你不能在这里使用JOIN,因为你没有可以参考的主表。我的解决方案使用UNION ALL来合并每个表的总数。

SELECT  CreatedDate, 
        CreatedBy,
        SUM(totalTable1) Total_of_table1, 
        SUM(totalTable2) Total_of_table2, 
        SUM(totalTable3) Total_of_table3, 
        SUM(totalTable4) Total_of_table4
FROM
        (
            SELECT  CreatedDate, CreatedBy, 
                    COUNT(*) totalTable1,
                    0 totalTable2,
                    0 totalTable3,
                    0 totalTable4
            FROM    table1
            GROUP   BY CreatedDate, CreatedBy
            UNION ALL
            SELECT  CreatedDate, CreatedBy, 
                    0 totalTable1,
                    COUNT(*) totalTable2,
                    0 totalTable3,
                    0 totalTable4
            FROM    table2
            GROUP   BY CreatedDate, CreatedBy
            UNION ALL
            SELECT  CreatedDate, CreatedBy, 
                    0 totalTable1,
                    0 totalTable2,
                    COUNT(*) totalTable3,
                    0 totalTable4
            FROM    table3
            GROUP   BY CreatedDate, CreatedBy
            UNION ALL
            SELECT  CreatedDate, CreatedBy, 
                    0 totalTable1,
                    0 totalTable2,
                    0 totalTable3,
                    COUNT(*) totalTable4
            FROM    table4
            GROUP   BY CreatedDate, CreatedBy
        ) s
GROUP   BY CreatedDate,  CreatedBy
ORDER   BY CreatedBy, CreatedDate