mysql-计算两个日期之间的差

时间:2019-03-02 10:16:42

标签: mysql sql select difference

我有一个如下表。

CREATE TABLE `table_growth` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `timestamp` datetime DEFAULT CURRENT_TIMESTAMP,
  `table_name` varchar(50) DEFAULT NULL,
  `rows` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=184 DEFAULT CHARSET=utf8

表中的行示例:

+-----+---------------------+--------------------------+-------+
| id  | timestamp           | table_name               | rows  |
+-----+---------------------+--------------------------+-------+
| 110 | 2019-03-01 06:00:00 | attachments              |   640 |
| 111 | 2019-03-01 06:00:00 | contacts                 |     0 |
| 112 | 2019-03-01 06:00:00 | copy_menuitem_options    |  3038 |
| 113 | 2019-03-01 06:00:00 | copy_menuitem_suboptions |  9779 |
| 114 | 2019-03-01 06:00:00 | copy_menuitems           | 12118 |
| 115 | 2019-03-02 06:00:00 | attachments              |   638 |
| 116 | 2019-03-02 06:00:00 | contacts                 |     0 |
| 117 | 2019-03-02 06:00:00 | copy_menuitem_options    |  3039 |
| 118 | 2019-03-02 06:00:00 | copy_menuitem_suboptions |  9789 |
| 119 | 2019-03-02 06:00:00 | copy_menuitems           | 12128 |
+-----+---------------------+--------------------------+-------+

我想计算2天之间的diff(rows)。像date(timestamp)='2019-03-02' - date(timestamp)='2019-03-01'

预期结果

table_name              | Rows Diff
------------------------------
attachments             | 2
contacts                | 0           
copy_menuitem_options   | 1
copy_menuitem_suboptions| 10 
copy_menuitems          | 10 

我尝试了这些查询,但是失败了。

 SELECT x.table_name
     , (y.rows-x.rows)as diff
  FROM dbadmin.table_growth x
  JOIN dbadmin.table_growth y
    ON y.id = x.id
   AND DATE(y.timestamp) = '2019-03-02' 
 WHERE DATE(x.timestamp) = '2019-03-01';

select x.table_name, (y.rows - x.rows) as doff
from table_growth x join
table_growth y on y.id=x.id and DATE(y.timestamp) = '2019-03-02' 
WHERE DATE(x.timestamp) = '2019-03-01';

3 个答案:

答案 0 :(得分:1)

您的第二个查询在正确的轨道上,但是联接条件部分处于关闭状态。您应该断言表名而不是ID匹配:

SELECT
    x.table_name,
    (x.rows - y.rows) AS diff
FROM table_growth x
INNER JOIN table_growth y
    ON x.table_name = y.table_name and
       DATE(y.timestamp) = '2019-03-02'
WHERE
    DATE(x.timestamp) = '2019-03-01';

注意:您当前的输出有点模糊,因为不清楚哪个rows值是差异中的第一位,还是不清楚您是否要报告绝对值。

答案 1 :(得分:0)

这将起作用;

select distinct a.table_name,(a.rows-b.rows) diff from table_growth a,table_growth b 
where a.table_name=b.table_name;

答案 2 :(得分:0)

如果每个日期只有一行,那么这可能是最快的方法:

SELECT g.table_name,
       SUM(CASE WHEN DATE(g.timestamp) = '2019-03-02'
                THEN g.rows 
                WHEN DATE(g.timestamp) = '2019-03-01'
                THEN -g.rows
                ELSE 0
           END) as diff
FROM dbadmin.table_growth g
WHERE g.timestamp >= '2019-03-01' AND
      g.timestamp < '2019-03-03'
GROUP BY g.table_name;

尤其是,这可以利用table_growth(timestamp, table_name, rows)上的索引。