为什么我从连接的表中得到错误的值?

时间:2013-05-24 15:55:52

标签: php mysql sql

这是我的MySQL架构

CREATE TABLE IF NOT EXISTS `sales` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `date` date NOT NULL,
  `total_tax` decimal(25,2) NOT NULL,
  `total` decimal(25,2) NOT NULL,
  `total_tax2` decimal(25,2) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=38 ;

INSERT INTO `sales` (`id`, `date`, `total_tax`, `total`, `total_tax2`) VALUES
(1, '2013-02-14', 6, 100, 21),
(2, '2013-02-18', 6, 100, 21),
(3, '2013-03-01', 6, 100, 21),
(4, '2013-03-07', 6, 100, 21),
(5, '2013-03-28', 6, 100, 21),
(6, '2013-03-28', 6, 100, 21),
(7, '2013-04-04', 6, 100, 21);

CREATE TABLE IF NOT EXISTS `purchases` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `date` date NOT NULL,
  `total` decimal(25,2) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=15 ;

INSERT INTO `purchases` (`id`, `date`, `total`) VALUES
(1, '2013-02-15', 150),
(2, '2013-02-16', 18),
(3, '2013-03-05', 80),
(4, '2013-03-09', 50),
(5, '2013-03-16', 500),
(6, '2013-03-22', 200);

我想通过加入sales.total上的表格,逐月获得total_taxtotal_tax2purchases.totaldate的总价值。我正在尝试这个SQL查询:

SELECT date_format( sales.date, '%b %Y' ) AS MONTH,
SUM( COALESCE( sales.total, 0 ) ) AS sales,
SUM( COALESCE( purchases.total, 0 ) ) AS purchases,
SUM( COALESCE( total_tax, 0 ) ) AS tax1,
SUM( COALESCE( sales.total_tax2, 0 ) ) AS tax2
FROM sales
LEFT JOIN purchases
ON date_format(purchases.date, '%b %Y' ) = date_format(sales.date, '%b %Y' )
WHERE sales.date >= date_sub( now( ) , INTERVAL 12 MONTH )
GROUP BY date_format( purchases.date, '%b %Y' )
ORDER BY date_format( sales.date, '%m' ) ASC

获得结果

Feb 2013    400     336     24  84
Mar 2013    1600    3320    96  336
Apr 2013    100     0   6   21

为什么我得到这些不正确的值?

SQL Fiddle

1 个答案:

答案 0 :(得分:5)

您将按表格日期的月份加入,这意味着您要乘以正在汇总的行。您可以先执行聚合,也可以按表的键加入:

SELECT S.Month,
       S.sales,
       ISNULL(P.purchases,0) purchases,
       S.tax1,
       S.tax2
FROM (  SELECT  date_format(date, '%b %Y') Month,
                SUM(total) Sales,
                SUM(total_tax) tax1,
                SUM(total_tax2) tax2
        FROM sales
        WHERE sales.date >= date_sub( now( ) , INTERVAL 12 MONTH )
        GROUP BY date_format(date, '%b %Y')) S
LEFT JOIN ( SELECT  date_format(date, '%b %Y') Month,
                    SUM(total) purchases
            FROM purchases
            GROUP BY date_format(date, '%b %Y')) P
    ON S.Month = P.Month
GROUP BY S.Month
ORDER BY S.Month

Here is the sqlfiddle使用此选项。