如何在没有where子句的情况下从两个不同的表中计算两列的总和?

时间:2013-08-15 05:27:14

标签: mysql sql

我使用以下sql语句对来自两个不同表的两列中的值求和。声明可以输出,但不能输出所需的结果。

SELECT
SUM(`_income`.rate) AS Income,
SUM(`_expense`.rate) AS Expense,
SUM(_income.rate)-SUM(_expense.rate) AS Balance
FROM `_expense`, `_income`

我的表在这里:

CREATE TABLE IF NOT EXISTS `_expense` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `item` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `qnty` int(11) NOT NULL,
  `rate` int(11) NOT NULL,
  `date` date NOT NULL,
  `CreatedByPHPRunner` int(11) NOT NULL,
  `remarks` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

-

- 转储表_expense

的数据
INSERT INTO `_expense` (`id`, `item`, `qnty`, `rate`, `date`, `CreatedByPHPRunner`,   `remarks`) VALUES
(2, 'Maian', 2, 20, '2013-08-15', 0, 'A tui kher mai'),
(3, 'Battery', 1, 2100, '2013-08-15', 0, 'A lian chi');

-

- 表_income

的表结构
CREATE TABLE IF NOT EXISTS `_income` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `items` varchar(100) DEFAULT NULL,
  `qnty` int(11) DEFAULT NULL,
  `rate` int(11) DEFAULT NULL,
  `date` date DEFAULT NULL,
  `remarks` varchar(255) DEFAULT NULL,
  `CreatedByPHPRunner` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

-

- 转储表_income

的数据
INSERT INTO `_income` (`id`, `items`, `qnty`, `rate`, `date`, `remarks`, `CreatedByPHPRunner`) VALUES
(1, 'TV chhe siam', 1, 1500, '2013-08-15', 'Ka hniam hrep', NULL),
(2, 'First Star', 1, 25, '2013-08-15', 'A loose-in aw', NULL),
(3, 'Mobile Chhe siam', 2, 200, '2013-08-13', 'Nokia chhuak ho a nia', NULL),
(4, 'Internet hman man', 1, 1500, '2013-08-14', 'Ka net min hman sak a', NULL);

1 个答案:

答案 0 :(得分:7)

这应该这样做:

select income, expense, income-expense balance
from (select sum(rate) income
      from _income) i
JOIN (select sum(rate) expense
      from _expense) e