1

我有四张桌子,这里是

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

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

4

1 回答 1

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
于 2013-03-11T12:49:27.753 回答