Mysql - 减去前一天的值

时间:2013-11-15 17:03:23

标签: mysql

我希望在两天内减去在session ='morning'中输入的anem_reading值,i.date = today和x.date昨天的值显示为'run',但sql代码中的错误是thre

 SELECT x.date,

   i.anem_reading - (SELECT anem_reading
              FROM reg_data x
              WHERE date = DATE_SUB(now(), INTERVAL 1 DAY)
              AND x.(session=morning) = (i.session=morning)
              ORDER BY date 
              LIMIT 1) run FROM reg_data i;



  CREATE TABLE `reg_data` (
  `date` varchar(10) NOT NULL,
  `session` varchar(10) NOT NULL,
  `time` time default NULL,
  `temp_air` float NOT NULL,
  `rel_humid` float NOT NULL,
  `soil_temp_5` float NOT NULL,
  `soil_temp_20` float NOT NULL,
  `soil_temp_30` float NOT NULL,
  `soil_temp_60` float NOT NULL,
  `air_pressure` float NOT NULL,
  `anem_reading` float NOT NULL,
  `dry_temp` float NOT NULL,
  `wet_temp` float NOT NULL,
   PRIMARY KEY  (`date`,`session`)
   ) ENGINE=MyISAM DEFAULT CHARSET=latin1;  

2 个答案:

答案 0 :(得分:1)

请试试这个:

select a.dateToday, i.anem_reading - a.anem_reading
from              
(             
SELECT anem_reading
FROM reg_data x
WHERE date = DATE_SUB(now(), INTERVAL 1 DAY)              
  and session='morning'
  limit 1
) a,
    reg_data i
where i.session = 'morning'

答案 1 :(得分:0)

为样式翻译相同的查询(希望准确):

SELECT 
  /**/x.date,/**/ -- this is a bug and should be fixed (i?)
  i.anem_reading - (
    SELECT x.anem_reading
    FROM reg_data AS x
    WHERE x.date = DATE_SUB(now(), INTERVAL 1 DAY) -- relative to i.date?
      AND (x.session = x.morning) = (i.session = i.morning)
    ORDER BY x.date -- should be DESC?
    LIMIT 1
  ) AS run 
FROM reg_data AS i
;