2014-04-04 29 views
0

嗨我试图遵循几个示例如何解决我的问题,但没有成功。减去最后两行并将结果写入新表MySQL

因此,这里的情况

我有一个表如下(表将每月增加)

mysql> DESCRIBE poraba; 
+------------+------------+------+-----+-------------------+-----------------------------+ 
| Field  | Type  | Null | Key | Default   | Extra      | 
+------------+------------+------+-----+-------------------+-----------------------------+ 
| mesec  | timestamp | NO |  | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP | 
| voda_mrzla | varchar(5) | NO |  | NULL    |        | 
| voda_topla | varchar(5) | NO |  | NULL    |        | 
+------------+------------+------+-----+-------------------+-----------------------------+ 

用下面vaules

mysql> SELECT * FROM poraba; 
+---------------------+------------+------------+-----------+ 
| mesec    | voda_mrzla | voda_topla | id_poraba | 
+---------------------+------------+------------+-----------+ 
| 2014-03-03 16:19:08 | 5985  | 3417  |   1 | 
| 2014-04-03 20:57:51 | 5978  | 3412  |   2 | 

我想执行以下操作。始终只在最后输入。所以我得到当前和上个月的区别。

例如:

voda_mrzla (from 2014-04-03) - voda_mrzla (from 2014-03-03) = difference_cold 
voda_topla (from 2014-04-03) - voda_topla (from 2014-03-03) = difference_hot 

mysql> DESCRIBE usage_per_month; 
+-----------------+-------------+------+-----+---------+-------+ 
| Field   | Type  | Null | Key | Default | Extra | 
+-----------------+-------------+------+-----+---------+-------+ 
| difference_cold | varchar(10) | NO |  | NULL |  | 
| difference_hot | varchar(10) | NO |  | NULL |  | 

回答

0

它看起来像差数据库设计。你至少应该有一个增量值为id的id列。这样(尽管如此麻烦)的查询会更容易一些。鉴于你目前的设计,你需要做的是(非常,非常慢和低效):

insert into usage_per_month 
select a.voda_mrzla - b.voda_mrzla, a.voda_topla - voda_topla 
from (select * from poraba where mesec = (select max(mesec) from poraba)) as a, 
(select * from poraba where mesec = (select max(mesec) from poraba where mesec <> (select max(mesec) from poraba))) as b; 

是的,这是丑陋的。

0

更改所有“VARCHAR”中的“INT”,并称ID的所有表并执行以下解决我的问题

INSERT INTO usage_per_month (difference_cold, difference_hot) 
SELECT p1.voda_mrzla - p2.voda_mrzla AS poraba_mrzla1, p1.voda_topla - p2.voda_topla AS poraba_topla1 FROM poraba p1 
    LEFT JOIN poraba p2 ON p2.`id_poraba` = (
    SELECT MAX(`id_poraba`) FROM poraba p3 WHERE p3.`id_poraba` < p1.`id_poraba` 
) ORDER BY p1.id_poraba DESC LIMIT 1 

TNX的帮助!