1

我正在使用以下 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);
4

1 回答 1

7

这应该这样做:

select income, expense, income-expense balance
from (select sum(rate) income
      from _income) i
JOIN (select sum(rate) expense
      from _expense) e
于 2013-08-15T05:34:09.770 回答