0

我有一个收入和支出表。我想在一个查询中同时选择它们,并获得按月分组的income.amount 字段和expense.amount 字段之间的差异。这样查询将返回一个结果,即基于月份计算的收入总额中的费用总额。我使用了两种方法,但没有奏效。找到以下内容:

SELECT *, count(*), sum(`transaction`.amount) as tiamount,  sum(expenditure.amount) as teamount, monthname(`transaction`.date) as mni, monthname(expenditure.date) as mne 
FROM `transaction`, expenditure 
WHERE month(expenditure.`date`)=month(`transaction`.`date`) and month(`transaction`.`date`)=month(expenditure.`date`) 
GROUP BY monthname(`transaction`.date) ORDER BY `transaction`.date Desc

另一个是:

SELECT count(*), `transaction`.date, sum(`transaction`.amount) as tiamount, sum(`transaction`.amount - expenditure.amount) as diff, monthname(`transaction`.date) as mni 
FROM `transaction` left join expenditure on monthname(`transaction`.date) = monthname(expenditure.date)
UNION ALL
SELECT count(*), expenditure.date, sum(expenditure.amount) as teamount, sum(`transaction`.amount - expenditure.amount) as diff, monthname(expenditure.date) as mne 
FROM expenditure left join `transaction` on monthname(`transaction`.date) = monthname(expenditure.date)

任何帮助,将不胜感激。谢谢。

4

1 回答 1

0

好的,谢谢大家。我解决了这个问题。每次加载页面时,它都会检查表 balance2 是否已经存在,如果存在,则会立即删除并重新创建

mysql_query($query_truncate = "drop table IF EXISTS balance2");
    $create= "CREATE TABLE  balance2 (
    `id` INT( 11 ) NOT NULL AUTO_INCREMENT ,
     `count` VARCHAR( 50 ) NOT NULL DEFAULT  '',
     `month` VARCHAR( 50 ) NOT NULL DEFAULT  '',
     `amount` VARCHAR( 50 ) NOT NULL DEFAULT  '',
     `amount2` VARCHAR( 20 ) NOT NULL ,
     `type` VARCHAR( 20 ) NOT NULL ,
     `date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
    PRIMARY KEY (  `id` )
    ) ENGINE = INNODB DEFAULT CHARSET = latin1";
    mysql_query($create);

然后在使用INSERT INTO...SELECT...UNION SELECT.... 从费用和收入表中选择插入到新创建的余额表中。

query_merge = "INSERT INTO  balance2 (count, date, amount, amount2, month, type)
(SELECT count(*), t.date, sum(t.amount),0 ,monthname(t.date), 'income'
FROM `transaction` as t group by month(t.date))
UNION
(SELECT count(*), e.date, 0,sum(e.amount) as teamount, monthname(e.date) as mne, 'expense'
FROM expenditure as e group by month(e.date))";

这非常有效,因为它给了我想要的所有结果。认为它可能会帮助别人。再见

于 2013-06-20T17:01:34.833 回答