查询差异

时间:2018-09-11 08:25:02

标签: mysql sql

我有两个表:

  • 表1:创建的ID

  • 表2:id,modi

    
+------------+----------+
|    id      | created  |
+------------+----------+
|    1       | 18/01/01 |
|    2       | 18/01/01 |
|    3       | 18/01/01 |
|    4       | 18/01/01 |
+------------+----------+  
    
+------------+----------+
|    id      | modi     |
+------------+----------+
|    1       | 18/01/02 |
|    4       | 18/01/02 |
|    1       | 18/01/03 |
|    2       | 18/01/03 |
|    3       | 18/01/04 |
|    2       | 18/01/04 |
|    2       | 18/01/05 |
+------------+----------+   

我需要一个查询(MySQL),该查询可以按天将每个用户修改日志需要的时间打印出来。例如1天-3位用户,2天-7位用户,等等...

    
+------------+----------+
|    days    | num_id   |
+------------+----------+
|    1       | 2        |
|    2       | 1        |
|    3       | 1        |
+------------+----------+

我设法做到了:

select datediff(table1.id, table2.modi) as date_diff, count(*) as nums
from table1, table2
where table1.id = table2.id
group by date_diff

问题在于,除了第一个条目外,它还包含第二个条目(或更多),但是我只希望包含第一个条目。

谢谢。

2 个答案:

答案 0 :(得分:0)

只需在查询中添加一个Join Left。 :)

答案 1 :(得分:0)

您需要为datediff功能使用适当的列

select datediff(table3.modi,table1.created) as date_diff, count(*) as nums
    from table1 left  join 
    (
    select id,min(modi) as modi  from table2 group by id
    ) 
    as table3
    on table1.id = table3.id
    group by date_diff