小编典典

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

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);

阅读 239

收藏
2021-03-23

共1个答案

小编典典

这应该做到这一点:

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