联合中的减法或表php / mysql中的联接

时间:2013-06-04 16:35:18

标签: php mysql join union

我有一张收入和支出表。我想在一个查询中选择它们,并获得按月收入的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)

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

1 个答案:

答案 0 :(得分: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))";

这完美地运作,因为它给了我想要的所有结果。 认为它可能会帮助别人。见你