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

mysql - calculate difference between two dates

我有一个 table,如下所示。

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

table 中的行示例:

+-----+---------------------+--------------------------+-------+
| 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';

您的第二个查询在正确的轨道上,但连接条件部分关闭。您应该断言 table 名称,而不是 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 值在差异中排在第一位,或者您是否想报告绝对值。

这会起作用;

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

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

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) 上的索引。