您好我尝试按照几个例子来解决我的问题,但没有成功。
所以这是情况
我有一张包含以下内容的表格(每个月都会增加表格)
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 :(得分:0)
看起来糟糕的数据库设计。您至少应该有一个带有增量值的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;
是的,这很难看。
答案 1 :(得分: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寻求帮助!