这是我的 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_tax
、total_tax2
和 purchases.total
的总值(value)通过在 date
上连接表格,按月列出 code>。我正在尝试这个 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
为什么我会得到这些不正确的值?
最佳答案
您将按表日期的月份进行连接,这意味着您将求和的行相乘。您可以预先执行聚合,也可以通过表的键进行连接:
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使用此选项。
关于php - 为什么我从连接表中得到错误的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16739034/